Monday, November 30, 2020

Java Get Next And Previous Dates

1. Overview

In this tutorial, We'll learn how to get next and previous dates from the current date or for any date in old and new java 8 beyond.

Sometime it is referred as tomorrows or yesterdays date is needed for a particular date. 

To solve this problem, we should be clear on the input date format. If the date is in string format then first need to get the date format in string and next need to convert into java Date.

Sometimes, input can be date in the format of java.util.Date or java.time.LocalDate.

Let us explore the all possible ways to get the old and new dates from the given date.

Java Get Next And Previous Dates


2. Getting the Next & Previous Date from java.util.Date


First, we will look at date in string format and next direct Date() object.


2.1 Date in String Format


Assume that input date is given in string format and we will print the next and previous dates also in the same string format.

Steps to get the next date:

Step 1: Convert the string to date
Step 2: Get the milliseconds from date and add 1 day milliseconds (24 * 60 * 60 * 1000) 
Step 3: Next, covert this addition of milliseconds to date and this will be next date for the given date.
Step 4: Convert next date to string form as input.

Steps to get the previous date:

Step 1: Convert the string to date
Step 2: Get the milliseconds from date and subtract 1 day milliseconds (24 * 60 * 60 * 1000) 
Step 3: Next, covert this subtraction of milliseconds to date and this will be previous date for the given date.
Step 4: Convert next date to string form as input.

The below examples covers how to increment or decrement a date by one day in java.


package com.javaprogramto.java8.dates.nextprevious;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class NextPreviousFromStringDate {

	// Millseconds in a day
	private static final long ONE_DAY_MILLI_SECONDS = 24 * 60 * 60 * 1000;

	// date format
	private static final String DATE_FORMAT = "yyyy-MM-dd";

	public static void main(String[] args) throws ParseException {

		// Date in string format as "YYYY-MM-DD"
		String dateInString = "2021-12-12";

		// Simple date formatter
		SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
		Date date = dateFormat.parse(dateInString);

		// Getting the next day and formatting into 'YYYY-MM-DD'
		long nextDayMilliSeconds = date.getTime() + ONE_DAY_MILLI_SECONDS;
		Date nextDate = new Date(nextDayMilliSeconds);
		String nextDateStr = dateFormat.format(nextDate);

		// Getting the previous day and formatting into 'YYYY-MM-DD'
		long previousDayMilliSeconds = date.getTime() - ONE_DAY_MILLI_SECONDS;
		Date previousDate = new Date(previousDayMilliSeconds);
		String previousDateStr = dateFormat.format(previousDate);

		// printing the input, tomorrow and yesterday's date as strings. 
		System.out.println("Given Date : " + dateInString);
		System.out.println("Next Date : " + nextDateStr);
		System.out.println("Previous Date : " + previousDateStr);
	}
}
 
Output:
Given Date : 2021-12-12
Next Date : 2021-12-13
Previous Date : 2021-12-11
 

2.2 Get Next and Previous date from java.util.Date format


Next example is to get the next and previous dates from java.util.Date as current date time.
package com.javaprogramto.java8.dates.nextprevious;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class NextPreviousFromUtilDate {

	// Millseconds in a day
	private static final long ONE_DAY_MILLI_SECONDS = 24 * 60 * 60 * 1000;

	// date format
	private static final String DATE_FORMAT = "yyyy-MM-dd";

	public static void main(String[] args) throws ParseException {

		// current date time
		Date currentDate = new Date();

		// Simple date formatter to show in the input and output dates to redable form.
		SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);

		// Getting the next day and formatting into 'YYYY-MM-DD'
		long nextDayMilliSeconds = currentDate.getTime() + ONE_DAY_MILLI_SECONDS;
		Date nextDate = new Date(nextDayMilliSeconds);
		String nextDateStr = dateFormat.format(nextDate);

		// Getting the previous day and formatting into 'YYYY-MM-DD'
		long previousDayMilliSeconds = currentDate.getTime() - ONE_DAY_MILLI_SECONDS;
		Date previousDate = new Date(previousDayMilliSeconds);
		String previousDateStr = dateFormat.format(previousDate);

		// printing the input, tomorrow and yesterday's date as strings.
		System.out.println("Current Date : " + dateFormat.format(currentDate));
		System.out.println("Next Date : " + nextDateStr);
		System.out.println("Previous Date : " + previousDateStr);
	}
}
 
Output:
Current Date : 2020-11-30
Next Date : 2020-12-01
Previous Date : 2020-11-29
 

3. Java 8 - Getting the Next & Previous Date


Next, How to get the tomorrow and yesterday dates in java 8.

First create a date object using LocalDate class. Next, call its plusDays(1) and minusDays(1) methods to get the next and previous dates in java.

These two methods are part of java 8 api and simplifies the processing of adding required number of days.

In our case, we need to add one day to get next date and mins one day to get previous date.

package com.javaprogramto.java8.dates.nextprevious;

import java.text.ParseException;
import java.time.LocalDate;

/**
 * How to get the next and previous dates in java 8?
 * 
 * @author javaprogramto.com
 *
 */

public class Java8NextPreviousDates {

	public static void main(String[] args) throws ParseException {

		// Obtaining current date
		LocalDate currentDate = LocalDate.now();

		// Getting the next date using plusDays() method
		LocalDate nextDate = currentDate.plusDays(1);

		// Getting the previous date using minusDays() method
		LocalDate previousDate = currentDate.minusDays(1);

		// printing the input, tomorrow and yesterday's dates
		System.out.println("Current Date : " + currentDate);
		System.out.println("Next Date : " + nextDate);
		System.out.println("Previous Date : " + previousDate);
	}
}
 
Output:
Current Date : 2020-11-30
Next Date : 2020-12-01
Previous Date : 2020-11-29
 


4. Conclusion


In this article, we've seen how to obtain the next and previous days from current date or any given time in traditional java.util.Date class and LocalDate in java 8.




Java 8 ZonedDateTime Examples

1. Overview

In this article, We'll learn what is ZonedDateTime class and how to use effectively Dates with timezones in java 8.

ZonedDateTime class also an immutable class similar to the other date time api classes in java 8 and above and every method in this class will result in a new instance for this class with copy of every value.

ZonedDateTime class represents the date and time with the time zone values. This class stores the date and time fields and precision to the nano seconds along with the time zone value (with zone offset value to avoid ambiguous situation in local date times).

Java 8 ZonedDateTime Examples



2.  Java 8 ZonedDateTime Class Methods


Next, let use see the commonly used methods from the ZonedDateTime class.

static ZonedDateTime now(): It is used to obtain the current date-time from the system clock in the default time-zone.

String format(DateTimeFormatter formatter): It is used to format this date-time using the specified formatter.

int get(TemporalField field): It is used to get the value of the specified field from this date-time as an int.

ZoneId getZone(): It is used to get the time-zone, such as 'Asia/Kolkata'.

ZonedDateTime withZoneSameInstant(ZoneId zone): It is used to return a copy of this date-time with a different time-zone, retaining the instant.

static ZonedDateTime of(LocalDate date, LocalTime time, ZoneId zone): It is used to obtain an instance of ZonedDateTime from a local date and time.

ZonedDateTime minus(long amountToSubtract, TemporalUnit unit): It is used to return a copy of this date-time with the specified amount subtracted.

ZonedDateTime plus(long amountToAdd, TemporalUnit unit): It is used to return a copy of this date-time with the specified amount added.

int getDayOfYear(): It is used to get the day-of-year field.

int getHour(): It is used to get the hour-of-day field.

long getLong(TemporalField field): It is used to get  the value of the specified field from this date-time as a long.

int getMinute(): It is used to get  the minute-of-hour field.

Month getMonth(): It is used to get  the month-of-year field using the Month enum.

int getMonthValue(): Gets the month-of-year field from 1 to 12.

int getNano(): It is used to get  the nano-of-second field.

ZoneOffset getOffset(): It is used to get  the zone offset, such as '+01:00'.

int getSecond(): It is used to get  the second-of-minute field.

int getYear(): It is used to get  the year field.

ZoneId getZone(): It is used to get  the time-zone, such as 'Europe/Paris'.


3. Java ZonedDateTime Examples


Next, write a simple programs on the each method to understand clearly.

3.1 Creating ZonedDateTime Objects


Use now() or of() method to create the objects for the ZonedDateTime class. You can create the zoned date time from LocalDate, LocalTime or LocalDateTime objects using of() method.

package com.javaprogramto.java8.dates.zoneddatetime;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class ZonedDateTimeCreateExample {

	public static void main(String[] args) {

		// Create ZonedDateTime Object - using current date and time from now()
		ZonedDateTime zonedDateTime = ZonedDateTime.now();
		System.out.println("ZonedDateTime current time value : " + zonedDateTime);

		// using of() method
		ZonedDateTime tokyoTime = ZonedDateTime.of(2025, 01, 01, 01, 01, 30, 1000, ZoneId.of("Asia/Tokyo"));
		System.out.println("Tokyo time : " + tokyoTime);

		// using of() method with localdate and localtime objects
		ZonedDateTime usaCentralTime = ZonedDateTime.of(LocalDate.now(), LocalTime.now(), ZoneId.of("America/Chicago"));
		System.out.println("chicago time : " + usaCentralTime);

		// using of() and LocalDateTime class
		ZonedDateTime estTime = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("America/New_York"));
		System.out.println("new york time : " + estTime);
	}
}
 
Output:
ZonedDateTime current time value : 2020-11-30T13:47:32.985595+05:30[Asia/Kolkata]
Tokyo time : 2025-01-01T01:01:30.000001+09:00[Asia/Tokyo]
chicago time : 2020-11-30T13:47:32.986627-06:00[America/Chicago]
new york time : 2020-11-30T13:47:32.991812-05:00[America/New_York]

 

3.2 How to get the timezone from DateTime


Use getZone() method to get the time zone used by the ZonedDateTime object. We can also get the off set value from ZoneId.getRules() method.

package com.javaprogramto.java8.dates.zoneddatetime;

import java.time.ZoneId;
import java.time.ZonedDateTime;

public class GetTimezoneExample {

	public static void main(String[] args) {
		// Create object using of() method
		ZonedDateTime zonedtime = ZonedDateTime.of(2023, 01, 01, 01, 01, 30, 1000, ZoneId.of("America/Chicago"));

		// Getting timezone in string
		ZoneId currentZoneId = zonedtime.getZone();

		// print the value onto console
		System.out.println("Get timezone : " + currentZoneId.getId());

		// printing the offset value
		System.out.println("Timezone offset value : " + currentZoneId.getRules());
	}
}
 
Output:
Get timezone : America/Chicago
Timezone offset value : ZoneRules[currentStandardOffset=-06:00]
 

3.3 Timezone Conversion Using ZonedDateTime


Let us convert one LocalDateTime value from IST to EST timezone.  Use withZoneSameInstant() method to convert date from one timezone to another.
package com.javaprogramto.java8.dates.zoneddatetime;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class TimezoneConversionExample {

	public static void main(String[] args) {

		// Getting the current timezone.
		LocalDateTime localDateTime = LocalDateTime.now();

		// IST zone id
		ZoneId istZoneId = ZoneId.of("Asia/Kolkata");

		// Creating IST timezone datetime
		ZonedDateTime istTime = ZonedDateTime.of(localDateTime, istZoneId);

		// print ist time
		System.out.println("IST time : " + istTime);

		// creating est time zoneId.
		ZoneId estZoneId = ZoneId.of("America/New_York");
		
		// converting the ist time to est time using withZoneSameInstant() method
		ZonedDateTime estTime = istTime.withZoneSameInstant(estZoneId);
		
		// print est time
		System.out.println("EST time : "+estTime);
	}
}
 
Output:
IST time : 2020-11-30T14:51:10.184574+05:30[Asia/Kolkata]
EST time : 2020-11-30T04:21:10.184574-05:00[America/New_York]
 

3.4 Adding n Time Units to ZonedDateTime


Use plus() method add n no of a specific time units to the ZonedDateTime.
package com.javaprogramto.java8.dates.zoneddatetime;

import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;

public class ZonedDateTimePlusExample {

	public static void main(String[] args) {

		// Create ZonedDateTime Object - using current date and time from now()
		ZonedDateTime zonedDateTime = ZonedDateTime.now();
		System.out.println("ZonedDateTime current time value : " + zonedDateTime);

		// using plusXXX() method
		ZonedDateTime daysAdded = zonedDateTime.plusDays(10);
		ZonedDateTime hoursAdded = zonedDateTime.plusHours(10);
		ZonedDateTime monthsAdded = zonedDateTime.plusMonths(1);
		ZonedDateTime yearsAdded = zonedDateTime.plusYears(2);

		System.out.println("Days added : "+daysAdded);
		System.out.println("Hours added : "+hoursAdded);
		System.out.println("Months added : "+monthsAdded);
		System.out.println("yearss added : "+yearsAdded);
		
		// Using plus(timeunit, value)
		ZonedDateTime secondsAdded = zonedDateTime.plus(10, ChronoUnit.SECONDS);
		ZonedDateTime weeksAdded = zonedDateTime.plus(2, ChronoUnit.WEEKS);
		
		System.out.println("Seconds added : "+secondsAdded);
		System.out.println("Weeks added : "+weeksAdded);
	}

}
 
Output:
ZonedDateTime current time value : 2020-11-30T15:06:24.319161+05:30[Asia/Kolkata]
Days added : 2020-12-10T15:06:24.319161+05:30[Asia/Kolkata]
Hours added : 2020-12-01T01:06:24.319161+05:30[Asia/Kolkata]
Months added : 2020-12-30T15:06:24.319161+05:30[Asia/Kolkata]
yearss added : 2022-11-30T15:06:24.319161+05:30[Asia/Kolkata]
Seconds added : 2020-11-30T15:06:34.319161+05:30[Asia/Kolkata]
Weeks added : 2020-12-14T15:06:24.319161+05:30[Asia/Kolkata]

 

3.5 Subtracting n Time Units to ZonedDateTime


Use minus() method to go back to previous dates or time units. This method will subtract the time unit on the given date.
package com.javaprogramto.java8.dates.zoneddatetime;

import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;

public class ZonedDateTimeMinusExample {

	public static void main(String[] args) {

		// Create ZonedDateTime Object - using current date and time from now()
		ZonedDateTime zonedDateTime = ZonedDateTime.now();
		System.out.println("ZonedDateTime current time value : " + zonedDateTime);

		// using minusXXX() method
		ZonedDateTime daysSubtracted = zonedDateTime.minusDays(10);
		ZonedDateTime hoursSubtracted = zonedDateTime.minusHours(10);
		ZonedDateTime monthsSubtracted = zonedDateTime.minusMonths(1);
		ZonedDateTime yearsSubtracted = zonedDateTime.minusYears(2);

		System.out.println("Days Subtracted : "+daysSubtracted);
		System.out.println("Hours Subtracted : "+hoursSubtracted);
		System.out.println("Months Subtracted : "+monthsSubtracted);
		System.out.println("yearss Subtracted : "+yearsSubtracted);
		
		// Using minus(timeunit, value)
		ZonedDateTime secondsSubtracted = zonedDateTime.minus(10, ChronoUnit.SECONDS);
		ZonedDateTime weeksSubtracted = zonedDateTime.minus(2, ChronoUnit.WEEKS);
		
		System.out.println("Seconds Subtracted : "+secondsSubtracted);
		System.out.println("Weeks Subtracted : "+weeksSubtracted);
	}
}
 
Output:
ZonedDateTime current time value : 2020-11-30T16:57:08.648655+05:30[Asia/Kolkata]
Days Subtracted : 2020-11-20T16:57:08.648655+05:30[Asia/Kolkata]
Hours Subtracted : 2020-11-30T06:57:08.648655+05:30[Asia/Kolkata]
Months Subtracted : 2020-10-30T16:57:08.648655+05:30[Asia/Kolkata]
yearss Subtracted : 2018-11-30T16:57:08.648655+05:30[Asia/Kolkata]
Seconds Subtracted : 2020-11-30T16:56:58.648655+05:30[Asia/Kolkata]
Weeks Subtracted : 2020-11-16T16:57:08.648655+05:30[Asia/Kolkata]
 

3.6 Convert String to ZonedDateTime


Use ZonedDateTime.parse() method to convert string to ZonedDateTime in java.
package com.javaprogramto.java8.dates.zoneddatetime;

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class StringToZonedDateTimeExample {

	public static void main(String[] args) {

		// date in strig format
		String dateInString = "2020-11-16T16:57:08.648655+05:30[Asia/Kolkata]";

		// convert string to date format
		ZonedDateTime date = ZonedDateTime.parse(dateInString);

		// print the date onto console
		System.out.println("Final date created from string : " + date);

		// exception part.
		// trying into 
		String onlyDateInString = "2020-11-16";
		
		ZonedDateTime onlyDate = ZonedDateTime.parse(onlyDateInString, DateTimeFormatter.ISO_DATE);

		System.out.println("Only date" + onlyDate);
	}
}
 
Output:
Final date created from string : 2020-11-16T16:57:08.648655+05:30[Asia/Kolkata]
Exception in thread "main" java.time.format.DateTimeParseException: Text '2020-11-16' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 2020-11-16 of type java.time.format.Parsed
	at java.base/java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:2020)
	at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1955)
	at java.base/java.time.ZonedDateTime.parse(ZonedDateTime.java:598)
	at com.javaprogramto.java8.dates.zoneddatetime.StringToZonedDateTimeExample.main(StringToZonedDateTimeExample.java:23)
Caused by: java.time.DateTimeException: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 2020-11-16 of type java.time.format.Parsed
	at java.base/java.time.ZonedDateTime.from(ZonedDateTime.java:566)
	at java.base/java.time.format.Parsed.query(Parsed.java:235)
	at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1951)
	... 2 more
Caused by: java.time.DateTimeException: Unable to obtain ZoneId from TemporalAccessor: {},ISO resolved to 2020-11-16 of type java.time.format.Parsed
	at java.base/java.time.ZoneId.from(ZoneId.java:463)
	at java.base/java.time.ZonedDateTime.from(ZonedDateTime.java:554)
	... 4 more
 

4. Conclusion


In this article, we've seen how to use ZonedDateTime class in java 8 and what are the methods mostly used by the developers when working with the timezone dates.




Sunday, November 29, 2020

Java Instant Examples

1. Overview

In this tutorial, you'll learn what is instance class in java and how to create an object for Instant class.

This class models a single instantaneous point on the time-line. This might be used to record event time-stamps in the application.

Instant class holds the date time value with nano seconds so it requires the storage of a number larger than a long. To achieve this, the class stores a long representing epoch-seconds and an int representing nanosecond-of-second, which will always be between 0 and 999,999,999.
 
The epoch seconds are measured from the standard Java epoch of 1970-01-01T00:00:00Z value where instants after the epoch have positive values, and earlier instants have negative values.

This class has three constants fields such as EPOCH, MIN, MAX.

Java Instant Examples


2. Instant Class Methods


public static Instant now(): it is used to get the current date and time in Instance object. This value is optained from system clock.

Temporal adjustInto(Temporal temporal): It is used to adjust the specified temporal object to have this instant.
int get(TemporalField field): It is used to get the value of the specified field from this instant as an int.

boolean isSupported(TemporalField field): It is used to check if the specified field is supported.

Instant minus(TemporalAmount amountToSubtract): It is used to return a copy of this instant with the 
specified amount subtracted.

static Instant parse(CharSequence text): It is used to obtain an instance of Instant from a text string such as 2007-12-03T10:15:30.00Z.

Instant plus(TemporalAmount amountToAdd): It is used to return a copy of this instant with the specified amount added.

Instant with(TemporalAdjuster adjuster): It is used to return an adjusted copy of this instant.


3. Java Instant Examples

3.1 Instant Object Creation


Use now() method to get the object for Instant class from current system time.
package com.javaprogramto.java8.dates.instant;

import java.time.Instant;

public class InstantCreationExample {

	public static void main(String[] args) {

		// Creating instant object from now()
		Instant instant1 = Instant.now();
		System.out.println("Instant 1 value from now() - " + instant1);

		Instant instant2 = Instant.now();
		System.out.println("Instant 2 value from now() - " + instant2);
	}
}
 
Output:
Instant 1 value from now() - 2020-11-29T13:35:31.836392Z
Instant 2 value from now() - 2020-11-29T13:35:31.849851Z
 

3.2 Creating Instant From String - parse()


We can convert a String value to Instant object using Instant.parse() method. This parse() method takes string argument.
package com.javaprogramto.java8.dates.instant;

import java.time.Instant;

public class InstantParseExample {
	public static void main(String[] args) {

		// Creating instant object from parse()
		Instant instantFromStr1 = Instant.parse("2020-11-29T13:35:30.01Z");
		System.out.println("Instant 1 from string using parse() : " + instantFromStr1);

		Instant instantFromStr2 = Instant.parse("2020-12-29T13:35:31.00Z");
		System.out.println("Instant 2 from string using parse() : " + instantFromStr2);
	}
}
 
Output:
Instant 1 from string using parse() : 2020-11-29T13:35:30.010Z
Instant 2 from string using parse() : 2020-12-29T13:35:31Z
 

3.3 Create Instant from Epoch Second Value


Use ofEpochMilli() method to convert long epoch second value to Instant object.
package com.javaprogramto.java8.dates.instant;

import java.time.Instant;

public class InstantEpochSecondExample {
	public static void main(String[] args) {

		// Creating instant object from ofEpochMilli()
		Instant instantFromEpochSecond1 = Instant.ofEpochMilli(1606657474l);
		System.out.println("Instant 1 from Epoch Second value using  ofEpochMilli() : " + instantFromEpochSecond1);

		Instant instantFromEpochSecond2 = Instant.ofEpochMilli(1667137474l);
		System.out.println("Instant 2 from Epoch Second value using  ofEpochMilli() : " + instantFromEpochSecond2);
	}
}
 
Output:
Instant 1 from Epoch Second value using  ofEpochMilli() : 1970-01-19T14:17:37.474Z
Instant 2 from Epoch Second value using  ofEpochMilli() : 1970-01-20T07:05:37.474Z
 

3.4 Convert Instant to Long value


Use getEpochSecond() method to get the epoch second value from the existing instant object.
package com.javaprogramto.java8.dates.instant;

import java.time.Instant;

public class InstantGetEpochExample {
	public static void main(String[] args) {

		// Creating instant object from now()
		Instant instant1 = Instant.now();
		
		// Getting long value in epoch style from instant object
		long epoch1 = instant1.getEpochSecond();
		System.out.println("Instant 1 "+instant1);
		System.out.println("epoch 1 "+epoch1);

		// Another example to get the epoch value
		Instant instant2 = Instant.now();
		long epoch2 = instant2.getEpochSecond();
		System.out.println("Instant 2 "+instant2);
		System.out.println("epoch 2 "+epoch2);
	}
}
 
Output:
Instant 1 2020-11-29T13:56:40.849772Z
epoch 1 1606658200
Instant 2 2020-11-29T13:56:40.862042Z
epoch 2 1606658200
 

3.5 Adding n Time Units to Instant


Use plus() method to add a specific amount of time unit to the existing instant object.

package com.javaprogramto.java8.dates.instant;

import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class InstantPlusExample {
	public static void main(String[] args) {

		// Creating instant object from string using parse()
		Instant instant1 = Instant.parse("2020-11-29T13:56:40.11Z");

		// Adding 60 seconds
		Instant addedSeconds = instant1.plus(60l, ChronoUnit.SECONDS);
		System.out.println("Added 60 seconds : " + addedSeconds);

		// Another example to add 60 minutes
		Instant instant2 = Instant.parse("2020-11-29T13:56:40.11Z");

		// Adding 60 minutes
		Instant addedMinutes = instant2.plus(60l, ChronoUnit.MINUTES);
		System.out.println("Added 60 Minutues : " + addedMinutes);
	}
}
 
Output:
Added 60 seconds : 2020-11-29T13:57:40.110Z
Added 60 Minutues : 2020-11-29T14:56:40.110Z
 

3.6 Subtracting n Time Units from Instant


Use minus() method to subtract n number of a specific time units.
package com.javaprogramto.java8.dates.instant;

import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class InstantMinusExample {
	public static void main(String[] args) {

		// Creating instant object from string using parse()
		Instant instant1 = Instant.parse("2020-11-29T13:56:40.11Z");

		// Removing 60 seconds
		Instant addedSeconds = instant1.minus(60l, ChronoUnit.SECONDS);
		System.out.println("Minus 60 seconds : " + addedSeconds);

		// Another example to add 60 minutes
		Instant instant2 = Instant.parse("2020-11-29T13:56:40.11Z");

		// Subtracting 60 minutes
		Instant addedMinutes = instant2.minus(60l, ChronoUnit.MINUTES);
		System.out.println("Minus 60 Minutues : " + addedMinutes);
	}
}
 
Output:
Minus 60 seconds : 2020-11-29T13:55:40.110Z
Minus 60 Minutues : 2020-11-29T12:56:40.110Z
 

3.7 Comparing Instant Objects


Use equals() method to compare two Instance objects. And also we can use isAfter() and isBefore() methods to check if the instance 1 is before or after another Instance 2.
package com.javaprogramto.java8.dates.instant;

import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class ComoareInstancesExample {
	public static void main(String[] args) {

		// Creating instant object 1
		Instant instant1 = Instant.parse("2020-11-29T13:56:40.11Z");

		// Creating instant object 2
		Instant instant2 = Instant.parse("2022-11-30T13:56:40.11Z");

		// comparing two instants using equals() method
		boolean isEquals = instant1.equals(instant2);
		
		if(isEquals) {
			System.out.println("instant1 & instant2 are same");
		} else {
			System.out.println("instant1 & instant2 are not same");
		}
		
		// comparing Instants using isAfter()
		boolean isAfter = instant1.isAfter(instant2);
		
		if(isAfter) {
			System.out.println("instant1 is after instant2");
		} else {
			System.out.println("instant1 is not after instant2");
		}
		
		// comparing Instants using isBefore()
		boolean isBefore = instant1.isBefore(instant2);
		
		if(isBefore) {
			System.out.println("instant1 is before instant2");
		} else {
			System.out.println("instant1 is not before instant2");
		}
	}
}
 
Output:
instant1 & instant2 are not same
instant1 is not after instant2
instant1 is before instant2
 

4. Conclusion


In this article, You've seen how to use Instant class to work with the precise time lines and what are the methods needed to work with Instance objects.




Friday, November 27, 2020

Java 8 - Period and Duration Examples

1. Overview

In this tutorial, you'll learn Period and Duration usages in java 8 with examples.

Both of these classes are used for same purpose to represent the time based value and find the differences between two dates.

The main differences between these two is that Period class works with date based values where as Duration works with time based values.

Java 8 - Period and Duration



2. Period Class and Examples


The core point is that Period class represents the Year, Month and Day values of date.

2.1 Period object can be obtained from Period.between(startDate, endDate) method which takes two date objects.
2.2 Once you get the Period object then you can use getYear(), getMonth() and getDay() methods to get the specific part of the date object.
2.3 isNegative() method returns true if any of period value is negative value and that indicates that endDate > startDate.
2.4 isNegative() method returns false if the startDate > endDate
2.5 Use Period class methods of(), ofDays(), ofMonths(), ofYears(), ofWeeks() methods to get the Period object.
2.6 If you use ofDays() method, then other properties are set to 0. That means year value will become 0.
2.7 ofWeeks() method sets the no of days value internally to 7 * n where n is the no of weeks.
2.8 Period object can be created from a String value using parse() method. but string should be followed a syntax "PnYnMnD". Here, P indicates the Period, Y - years, M - months, D days. For example, "P2Y" means create a Period object with 2 years and others are set to 0.
2.9 Period values can be increased or decreased using plusXXX() and minusXXX() methods where XXX indicates any date unit.

Example:

In the below example, we have covered the all points described.
package com.javaprogramto.java8.dates.period;

import java.time.LocalDate;
import java.time.Period;

public class PeriodExample {

	public static void main(String[] args) {

		// Creating two dates
		LocalDate startDate = LocalDate.of(2020, 11, 01);
		LocalDate endDate = LocalDate.of(2021, 12, 31);
		
		// printing the start and end dates
		System.out.println("Start Date : "+startDate);
		System.out.println("End Date : "+endDate);

		// getting the differences between startDate and endDate
		Period periodDiff = Period.between(startDate, endDate);
		System.out.println("Period values - year : " + periodDiff.getYears() + ", Months : " + periodDiff.getMonths()
				+ ", Days : " + periodDiff.getDays());

		// checking the diff is negative
		boolean isNegative = periodDiff.isNegative();
		
		if(isNegative) {
			System.out.println("endDate is greater than startDate");
		} else {
			System.out.println("startDate is greater than endDate");
		}
		
		// Different ways to get Period objects
		Period period1 = Period.of(2,10, 30);
		Period periodDays = Period.ofDays(2);
		Period periodWeeks = Period.ofWeeks(10);

		System.out.println("period1 years : "+period1.getYears());
		System.out.println("periodDays days : "+periodDays.getDays());
		System.out.println("periodDays months : "+periodDays.getMonths());
		System.out.println("periodWeeks weeks : "+periodWeeks);
		System.out.println("periodWeeks days : "+periodWeeks.getDays());
		
		// Creating Period object from String
		Period periodParse1 = Period.parse("P2Y2M2D");
		System.out.println("Period days : "+periodParse1.getDays());
		
		Period periodParse2 = Period.parse("P3M4D");
		System.out.println("Period months : "+periodParse2.getMonths());
	}
}
 
Output:
Start Date : 2020-11-01
End Date : 2021-12-31
Period values - year : 1, Months : 1, Days : 30
startDate is greater than endDate
period1 years : 2
periodDays days : 2
periodDays months : 0
periodWeeks weeks : P70D
periodWeeks days : 70
Period days : 2
Period months : 3
 

3. Duration Class and Examples


Duration class represents time interval including seconds or milli or nano seconds. This is mainly suitable for time difference accuracy for smaller time ranges.

3.1 Use Duration.between(instant1, instant2) method to get the differences between two time Instants. This is the way to get the Duration object from between() method.
3.2 From the returned object from between() method, you can call getSeconds(), getNanoSeconds() methods to get the exact difference that make more precision.
3.3 And alos, you can pass LocalDateTime, LocalDate and LocalTime objects to the between() method which will return the new Duration object. This is another way to get the Duration object from different type of java 8 date time api classes.
3.4 You can use the isNegetive() method which returns boolean value as similar in Period class. If it returns true means instant2 is greater than instant1.
3.5 We can obtain the Duration object from another set of time units such as ofDays(), ofMinutes(), ofHours(), ofMillis(), ofNanos() methods.
3.6 Duration can be created from string using parse() method. This string should be in form of "PTnDTnHnMn.nS".
3.7 Duration object created from ofDays() or any method and this duration object can be converted into another time units using toHours(), toDays(), toMinutes(), toSeconds(). This time unit conversion is not available in Period class.
3.8 A duration is allowed to increase or decrease the time units using plus(), minus(), plusXXX() and minusXXX() methods.

Example:
package com.javaprogramto.java8.dates.duration;

import java.time.Duration;
import java.time.Instant;
import java.time.LocalTime;

public class DurationExample {

	public static void main(String[] args) {

		// creating Instance Objects
		Instant instant1 = Instant.parse("2020-11-30T20:30:40.00Z");
		Instant instant2 = Instant.parse("2020-11-30T20:31:40.00Z");

		// printing instnat objects
		System.out.println("Instant 1: " + instant1);
		System.out.println("Instant 2: " + instant2);

		// getting the time diff
		Duration duration = Duration.between(instant1, instant2);
		System.out.println("Diff between instance1 & instance2 in seconds : " + duration.getSeconds());

		// Diff b/w two LocalTime objects
		int nanos = Duration.between(LocalTime.now(), LocalTime.now()).getNano();
		System.out.println("Time diff in nanos : " + nanos);

		boolean isNegative = duration.isNegative();
		if (isNegative) {
			System.out.println("instant2 is greater than instant1");
		} else {
			System.out.println("instant1 is greater than instant2");
		}

		// Different ways to get Duration objects
		Duration durationDays = Duration.ofDays(2);
		Duration durationHours = Duration.ofHours(10);

		System.out.println("durationDays seconds : " + durationDays.getSeconds());
		System.out.println("durationDays nanos : " + durationDays.getNano());
		System.out.println("durationHours seconds : " + durationHours);
		System.out.println("durationHours seconds : " + durationHours.getSeconds());

		// Creating Duration object from String
		Duration durationParse1 = Duration.parse("PT2H");
		System.out.println("Duration seconds : " + durationParse1.getSeconds());

		Duration durationParse2 = Duration.parse("PT10S");
		System.out.println("Duration seconds : " + durationParse2.getSeconds());
	}
}
 
Output:
Instant 1: 2020-11-30T20:30:40Z
Instant 2: 2020-11-30T20:31:40Z
Diff between instance1 & instance2 in seconds : 60
Time diff in nanos : 32000
instant1 is greater than instant2
durationDays seconds : 172800
durationDays nanos : 0
durationHours seconds : PT10H
durationHours seconds : 36000
Duration seconds : 7200
Duration seconds : 10
 

4. Conclusion


In this article, you've seen the core differences between period and duration and when to use which one.

All the examples are show on GitHub.


Thursday, November 26, 2020

Java 8 - DateTimeFormatter Class to convert date to string

1. Overview

In this tutorial, you'll learn how to use DateTimeFormatter class to convert date to string in java 8.

As you know, DateTimeFormatter is also a final, an immutable and thread safe class.

What we'll learn here is 

What are the predefined date formats in DateTimeFormatter class?
How to use custom or user defined date patterns for date parsing to string?
How to use DateTimeFormatter class with FormatStyle enum?

How to convert LocalDateTime to String?
How to convert LocalDate to String?
How to convert LocalTime to String?
How to convert ZonedDateTime to String?

Java 8 - DateTimeFormatter Class to convert date to string



2. DateTimeFormatter Supported Predefined and Custom Formats


Below are the examples how to get the builtin and create custom formats. Use DateTimeFormatter.ofPattern(String) method to define our own date pattern and it takes the string argument to store the custom pattern.
package com.javaprogramto.java8.dates.datetimeformatter;

import java.time.format.DateTimeFormatter;

public class DateTimeFormatterExample {

	public static void main(String[] args) {

		// Predefined formats
		DateTimeFormatter predefinedFormat1 = DateTimeFormatter.BASIC_ISO_DATE;
		DateTimeFormatter predefinedFormat2 = DateTimeFormatter.ISO_DATE;
		DateTimeFormatter predefinedFormat3 = DateTimeFormatter.ISO_ZONED_DATE_TIME;

		// Custom formats
		DateTimeFormatter customFormat1 = DateTimeFormatter.ofPattern("yyyy-MMM");
		DateTimeFormatter customFormat2 = DateTimeFormatter.ofPattern("yyyy-MM-dd 'at' hh:mm a");
		DateTimeFormatter customFormat3 = DateTimeFormatter.ofPattern("yyyy-MM-dd z");

	}

}
 

3. DateTimeFormatter With FormatStyle Enum


As always builtin formats does not enough to fulfil the human readable formats. 
FormatStyle enum is defined withe 4 predefined formats FULL, LONG, MEDIUM and SHORT forms.

Step 1:
Get the right FormatStyle format.

Step 2:
Call DateTimeFormatter.ofLocalizedDate() and pass the FormatStyle to it as argument.

Step 3:
Create the LocalDateTime object using now() method and next call format() method on LocalDateTime instance by passing the formatter from the step 2.
package com.javaprogramto.java8.dates.datetimeformatter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

public class DateTimeFormatterFormatStyleExample {

	public static void main(String[] args) {

		FormatStyle full = FormatStyle.FULL;

		DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(full);
		
		LocalDateTime datetime = LocalDateTime.now();
		
		String fullForm = datetime.format(formatter);
		
		System.out.println("Full date form in string : "+fullForm);
	}

}
 
Output:
Full date form in string : Thursday, November 26, 2020
 

4. DateTimeFormatter - Convert LocalDateTime to String 


Next, Convert java 8 LocalDateTime to String format using DateTimeFormatter class in simple steps.

Step 1:
Create a custom date formatter using DateTimeFormatter.ofPattern() and pass the pattern to this method as "yyyy-MM-dd 'at' hh:mm a". Store the result into format variable.

Step 2:
Get the current date and time using LocalDateTime.now() and store the result in the datetime variable.

Step 3:
Finally, call datetime.format(formatter) method which returns the string which holds the date time value in our own format.
package com.javaprogramto.java8.dates.datetimeformatter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterLocalDateTimeToStringExample {

	public static void main(String[] args) {

		// Creating a custom formatter
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd 'at' hh:mm a");

		// Getting current date time using LocalDateTime.now() method
		LocalDateTime datetime = LocalDateTime.now();

		// converting date to string
		String fullForm = datetime.format(formatter);

		// printing date string form
		System.out.println("LocalDateTime form in string : " + fullForm);
	}

}
 
Output:
LocalDateTime form in string : 2020-11-26 at 08:55 PM
 

5. DateTimeFormatter - Convert LocalDate to String 


Next, Convert java 8 LocalDate to String format using DateTimeFormatter class in simple steps.

Step 1:
Create a custom date formatter using DateTimeFormatter.ofPattern() and pass the pattern as "yyyy-MMM" to this method. Store the result into format variable.

Step 2:
Get the current date and time using LocalDate.now() and store the result in the datetime variable.

Step 3:
Finally, call datetime.format(formatter) method which returns the string which holds the date time value in our own format.
package com.javaprogramto.java8.dates.datetimeformatter;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterLocalDateToStringExample {

	public static void main(String[] args) {

		// Creating a custom formatter
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMM");

		// Getting current date time using LocalDate.now() method
		LocalDate datetime = LocalDate.now();

		// converting date to string
		String fullForm = datetime.format(formatter);

		// printing date string form
		System.out.println("LocalDate form in string : " + fullForm);
	}
}
 
Output:
LocalDate form in string : 2020-Nov
 

6. DateTimeFormatter - Convert LocalTime to String 


Next, Convert java 8 LocalTime to String format "hh:ss a" using DateTimeFormatter class in simple steps.

Step 1:
Create a custom date formatter using DateTimeFormatter.ofPattern() and pass the pattern as "hh:ss a" to this method. Store the result into format variable.

Step 2:
Get the current date and time using LocalTime.now() and store the result in the datetime variable.

Step 3:
Finally, call datetime.format(formatter) method which returns the string which holds the date time value in our own format.
package com.javaprogramto.java8.dates.datetimeformatter;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterLocalTimeToStringExample {

	public static void main(String[] args) {

		// Creating a custom formatter
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:ss a");

		// Getting current date time using LocalTime.now() method
		LocalTime datetime = LocalTime.now();

		// converting date to string
		String fullForm = datetime.format(formatter);

		// printing date string form
		System.out.println("LocalTime form in string : " + fullForm);
	}
}
 
Output:
LocalTime form in string : 09:03 PM
 

7. DateTimeFormatter - Convert ZonedDateTime to String 


As steps as above but it converts ZonedDateTime to string format.

package com.javaprogramto.java8.dates.datetimeformatter;

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterZonedDateTimeToStringExample {

	public static void main(String[] args) {

		// Creating a custom formatter
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM/dd/yyyy 'at' hh:mm a z");

		// Getting current date time using ZonedDateTime.now() method
		ZonedDateTime datetime = ZonedDateTime.now();

		// converting date to string
		String fullForm = datetime.format(formatter);

		// printing date string form
		System.out.println("ZonedDateTime form in string : " + fullForm);
	}
}
 
Output:
ZonedDateTime form in string : Nov/26/2020 at 09:08 PM IST
 

8. Conclusion


In this article, We've seen how to use the DateTimeFormatter with different Java 8 DateTime API classes to convert them into String format.


Read Next


Wednesday, November 25, 2020

Java 8 LocalDateTime Class With Examples

1. Overview

In thus tutorial, You'll learn how to use and work with the LocalDateTime class in java 8.

LocalDateTime is a new class that added in java 8 Date Time api to simplify the date operations developer friendly such as converting date to string and string to data, adding days or months or years to date part, subtracting days, months or years to date.

And also you can add or remove hours, minutes or seconds. And also many more operations.

But, Java 8 LocalDate class does work and operated on only date format in such way for year, months and days.

And also another class Java 8 LocalTime class does and operates only date time part such as on hours, minutes and seconds or nano seconds.

Let us see the LocalDateTime class methods with example programs.

Java 8 LocalDateTime Class With Examples



2. Java 8 LocalDateTime Methods

LocalDateTime class is also an immutable date-time object like LocalDate and LocalTime and that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision. For example, the value "2nd October 2007 at 13:45.30.123456789" can be stored in a LocalDateTime.

String format(DateTimeFormatter formatter): It is used to format this date-time using the specified formatter.

int get(TemporalField field): It is used to get the value of the specified field from this date-time as an int.

LocalDateTime minusDays(long days): It is used to return a copy of this LocalDateTime with the specified number of days subtracted.

static LocalDateTime now(): It is used to obtain the current date-time from the system clock in the default time-zone.

static LocalDateTime of(LocalDate date, LocalTime time): It is used to obtain an instance of LocalDateTime from a date and time.

LocalDateTime plusDays(long days): It is used to return a copy of this LocalDateTime with the specified number of days added.

boolean equals(Object obj): It is used to check if this date-time is equal to another date-time.

public LocalDate toLocalDate(): It is used to convert from LocalDateTime to LocalDate

public LocalTime toLocalTime(): It is used to convert from LocalDateTime to LocalTime

public int getYear(): It is used to get the year value from datetime.

public int getHour(): It is used to get the hour value from range 0 to 23

public int getMinute(): It is used to get the minute value from range 0 to 59

public int getSecond(): It is used to get the second value from range 0 to 59

public int getNano(): It is used to get the nano value from range 0 to 999,999,999

public int getMonthValue(): It is used to get the month of the year value from range 1 to 12

public LocalDateTime plus(long amountToAdd, TemporalUnit unit): It is used to add the specified amount in the given time units. 

public LocalDateTime minus(long amountToSubtract, TemporalUnit unit): It is used to subtract the specified amount in the given time units. 


3. LocalDateTime Method Examples

Let explore the different date operations using LocalDateTime methods.

3.1 LocalDateTime Object Creation

Use now() or of() method to create the LocalDateTime object. now() method is to get the current date and time and of() method creates the LocalDateTime object though the date custom parameters passed to of() method.

package com.javaprogramto.java8.dates.localdatetime;

import java.time.LocalDateTime;

public class LocalDateTimeCreationExample {

	public static void main(String[] args) {
		// Creating the current date and time using LocalDateTime.now() method
		LocalDateTime currentDatetime = LocalDateTime.now();
		System.out.println("Current date time : "+currentDatetime);

		// Creating the future date and time using LocalDateTime.of() method
		LocalDateTime futureDateTime = LocalDateTime.of(2025, 01, 01, 00, 45);
		System.out.println("Future date time : "+futureDateTime);
	}
}
 

Output:

Current date time : 2020-11-25T20:12:01.733193
Future date time : 2025-01-01T00:45
 

From the output, you can see that now() method produces the output with the nano seconds where as of() method created the date using given time parameters without adding the nano seconds.

3.2 LocalDateTime To String Conversion

Converting LocalDateTime object to String is done using format() method. 

First, Create the LocalDateTime object using now() method.

Next, call format() method with the date format that is needed in string format.

Finally, stored the returned value into a String variable.

package com.javaprogramto.java8.dates.localdatetime;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeToStringExample {

	public static void main(String[] args) {
		// Getting current date and time using now() method
		LocalDateTime currentDatetime = LocalDateTime.now();
		System.out.println("Current date time : " + currentDatetime);

		// Date format in yyyy-MMM-dd hh:mm
		DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MMM-dd hh:mm");

		// converting LocalDateTime to String type
		String dateInStr = currentDatetime.format(dateFormat);
		System.out.println("Date time in string : " + dateInStr);
	}
}
 

Output:

Current date time : 2020-11-25T20:20:01.410561
Date time in string : 2020-Nov-25 08:20
 

In the above example, converted current date time into string format of "yyyy-MMM-dd hh:mm".

3.3 LocalDateTime.get() - Getting the specified date time part

Use get() method to get the specific time field from date time object as int value.

Enum ChronoField has several predefined constants and those can be passed to the get() method as shown in the below example to get year, month, day, hour, minute, second.

package com.javaprogramto.java8.dates.localdatetime;

import java.time.LocalDateTime;
import java.time.temporal.ChronoField;

public class LocalDateTimeToStringExample {

	public static void main(String[] args) {
		// Creating the date time object using of() method
		LocalDateTime datetime = LocalDateTime.of(2020, 10, 30, 23, 50, 59);
		System.out.println("Date time : " + datetime);

		//
		int year = datetime.get(ChronoField.YEAR);
		int month = datetime.get(ChronoField.MONTH_OF_YEAR);
		int day = datetime.get(ChronoField.DAY_OF_MONTH);
		int hour = datetime.get(ChronoField.HOUR_OF_DAY);
		int minute = datetime.get(ChronoField.MINUTE_OF_HOUR);
		int second = datetime.get(ChronoField.SECOND_OF_MINUTE);
		
		
		System.out.println("year : "+year);
		System.out.println("month : "+month);
		System.out.println("day : "+day);
		System.out.println("hour : "+hour);
		System.out.println("minute : "+minute);
		System.out.println("second : "+second);
	}
}
 

Output:

Date time : 2020-10-30T23:50:59
year : 2020
month : 10
day : 30
hour : 23
minute : 50
second : 59
 

3.4 LocalDateTime.plus() - Adding days or months or years or any date time part

This class has several methods to add date fields to the existing date and returns a new copy with the modified fields.

public LocalDateTime plus(long amountToAdd, TemporalUnit unit)

public LocalDateTime plusYears(long years)

public LocalDateTime plusMonths(long months)

public LocalDateTime plusWeeks(long weeks)

public LocalDateTime plusDays(long days)

public LocalDateTime plusHours(long hours)

public LocalDateTime plusMinutes(long minutes)

public LocalDateTime plusSeconds(long seconds)

public LocalDateTime plusNanos(long nanos)

Use the above methods as needed to modify the date time fields and the resulted new object gets the new changes.

package com.javaprogramto.java8.dates.localdatetime;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class LocalDateTimePlusExample {

	public static void main(String[] args) {
		// Creating the date time object using of() method
		LocalDateTime datetime = LocalDateTime.of(2020, 10, 30, 23, 50, 55);
		System.out.println("Date time : " + datetime);

		// using plus(long, TemporalUnit)
		LocalDateTime yearModifed = datetime.plus(2, ChronoUnit.YEARS);
		LocalDateTime monthsModifed = datetime.plus(2, ChronoUnit.MONTHS);

		// using plusXXX() methods
		LocalDateTime daysModifed = datetime.plusDays(2);
		LocalDateTime hoursModifed = datetime.plusHours(2);
		LocalDateTime minssModifed = datetime.plusMinutes(2);
		LocalDateTime secsModifed = datetime.plusSeconds(2);
		LocalDateTime nanosModifed = datetime.plusNanos(2);

		System.out.println("years added : " + yearModifed);
		System.out.println("months added: " + monthsModifed);
		System.out.println("days added : " + daysModifed);
		System.out.println("hours added : " + hoursModifed);
		System.out.println("minutes added : " + minssModifed);
		System.out.println("seconds added : " + secsModifed);
		System.out.println("nonos added : " + nanosModifed);
	}
}
 

Output:

Date time : 2020-10-30T23:50:55
years added : 2022-10-30T23:50:55
months added: 2020-12-30T23:50:55
days added : 2020-11-01T23:50:55
hours added : 2020-10-31T01:50:55
minutes added : 2020-10-30T23:52:55
seconds added : 2020-10-30T23:50:57
nonos added : 2020-10-30T23:50:55.000000002
 

3.5 LocalDateTime.minus() - Subtracting days or months or years or any date time part

This class has several methods to go back to the previous date fields to the existing date and returns a new copy with the modified fields.

public LocalDateTime minus(long amountToAdd, TemporalUnit unit)

public LocalDateTime minusYears(long years)

public LocalDateTime minusMonths(long months)

public LocalDateTime minusWeeks(long weeks)

public LocalDateTime minusDays(long days)

public LocalDateTime minusHours(long hours)

public LocalDateTime minusMinutes(long minutes)

public LocalDateTime minusSeconds(long seconds)

public LocalDateTime minusNanos(long nanos)

Use the above methods as needed to modify the date time fields and the resulted new object gets the new changes as plus() methods.

package com.javaprogramto.java8.dates.localdatetime;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class LocalDateTimeMinusExample {

	public static void main(String[] args) {
		// Creating the date time object using of() method
		LocalDateTime datetime = LocalDateTime.of(2020, 10, 30, 23, 50, 55);
		System.out.println("Date time : " + datetime);

		// using minus(long, TemporalUnit)
		LocalDateTime yearModifed = datetime.minus(2, ChronoUnit.YEARS);
		LocalDateTime monthsModifed = datetime.minus(2, ChronoUnit.MONTHS);

		// using minusXXX() methods
		LocalDateTime daysModifed = datetime.minusDays(2);
		LocalDateTime hoursModifed = datetime.minusHours(2);
		LocalDateTime minssModifed = datetime.minusMinutes(2);
		LocalDateTime secsModifed = datetime.minusSeconds(2);
		LocalDateTime nanosModifed = datetime.minusNanos(2);

		System.out.println("years substracted : " + yearModifed);
		System.out.println("months substracted: " + monthsModifed);
		System.out.println("days substracted : " + daysModifed);
		System.out.println("hours substracted : " + hoursModifed);
		System.out.println("minutes substracted : " + minssModifed);
		System.out.println("seconds substracted : " + secsModifed);
		System.out.println("nonos substracted : " + nanosModifed);
	}
}
 

Output:

Date time : 2020-10-30T23:50:55
years substracted : 2018-10-30T23:50:55
months substracted: 2020-08-30T23:50:55
days substracted : 2020-10-28T23:50:55
hours substracted : 2020-10-30T21:50:55
minutes substracted : 2020-10-30T23:48:55
seconds substracted : 2020-10-30T23:50:53
nonos substracted : 2020-10-30T23:50:54.999999998
 

4. Conclusion

In this article, you've seen most useful methods of LocalDateTime class in java 8 with examples.

All the methods of this class results in a new copy of date time object with the new changes applied to it and need to store it back to the new LocalDateTime reference.

GitHub

Read Next

Java 8 LocalDate Examples

Java 8 LocalTime Examples

Java 8 Date Time API Examples

LocalDateTime API

Tuesday, November 24, 2020

Java 8 LocalTime Class With Examples

1. Overview


In this article, you'll learn how to use LocalTime API in java 8 with example programs.

LocalTime is an immutable class that deals date and time object but is represents only time part of date and can be viewed as hour-minute-seconds.

Advantage of immutable class is that this can be operated with multiple threads so it is thread-safe.

If you want to store only the time data then this class is the right choice.

Java 8 LocalTime Class With Examples


2. Java 8 LocalTime Class

LocalTime is final class and implements Temporal, TemporalAdjuster, Comparable<LocalTime>, Serializable interfaces.

This follows the ISO-8601 calendar system without timezone.

Below are the methods that are used regularly by the developers.

public static LocalTime now(): This is used to create the time object by getting the current time with the default timezone.

public static LocalTime of(int hour, int minute, int second): This is also used to create the localtime object with the given time parameters.

LocalDateTime atDate(LocalDate date): It is used to combine this time with a date to create a LocalDateTime.

int compareTo(LocalTime other): It is used to compare this time to another time.

String format(DateTimeFormatter formatter): It is used to format this time using the specified formatter.

int get(TemporalField field): It is used to get the value of the specified field from this time as an int.

LocalTime minusHours(long hoursToSubtract): It is used to return a copy of this LocalTime with the specified number of hours subtracted.

LocalTime minusMinutes(long minutesToSubtract): It is used to return a copy of this LocalTime with the specified number of minutes subtracted.

LocalTime plusHours(long hoursToAdd): It is used to return a copy of this LocalTime with the specified number of hours added.

LocalTime plusMinutes(long minutesToAdd): It is used to return a copy of this LocalTime with the specified number of minutes added.

public String format(DateTimeFormatter formatter): It is used to convert LocalTime to String.

public long until(Temporal endExclusive, TemporalUnit unit): It is sued to calculates the amount of time until another time in terms of the specified unit.

public LocalTime truncatedTo(TemporalUnit unit): Truncation returns a copy of the original time with fields smaller than the specified unit set to zero. For example, truncating with the minutes unit will set the second-of-minute and nano-of-second field to zero.

public boolean isAfter(LocalTime other): It is used to check if this time is after the specified time.

public boolean isBefore(LocalTime other): It is used to check if this time is before the specified time.

public int compareTo(LocalTime other): This is used to compare this time to another time.



3. Java 8 LocalTime Examples


Next, let us use all the methods from LocalTime class along with the simple example programs.


3.1 Example 1: LocalTime Object Creation


LocalTime object can be created using two methods and those are now() and of() method.
now() method gets the time from the current system time with nano seconds where as of(int hours, int mins, int secs) method creates the time part from the given values.
package com.javaprogramto.java8.dates.localtime;

import java.time.LocalTime;

public class LocalTimeCreationExample {
	public static void main(String[] args) {

		// LocalTime object creation

		// Example 1 : Using now() method to get the current time
		LocalTime time1 = LocalTime.now();
		System.out.println("Time 1 using now() : " + time1);

		// Example 2 : Using of() method
		LocalTime time2 = LocalTime.of(20, 20, 20);
		System.out.println("Time 2 using of() : " + time2);

		// Example 3 : Using of() method
		LocalTime time3 = LocalTime.of(3, 30);
		System.out.println("Time 3 using of() : " + time3);
	}
}
 
Output:
Time 1 using now() : 21:21:58.526563
Time 2 using of() : 20:20:20
Time 3 using of() : 03:30
 

3.2 Example 2: Getting Time Parts from LocalTime Object


LocalTime class has a handy methods to get the hours, minutes and seconds from the local time object using getHour(), getMinute(), getSecond() methods.
package com.javaprogramto.java8.dates.localtime;

import java.time.LocalTime;

public class LocalTimeCreationExample {
	public static void main(String[] args) {

		// LocalTime object - creating from current time.
		LocalTime time = LocalTime.now();
		System.out.println("Current time : "+time);
		
		// Example 1 : Getting the hour from time.
		System.out.println("Hour : " + time.getHour());

		// Example 2 : Getting the minutes from time.
		System.out.println("Minutes : " + time.getMinute());

		// Example 3 : Getting the seconds from time.
		System.out.println("Seconds : " + time.getSecond());
	}
}
 
Output:
Current time : 21:30:08.328088
Hour : 21
Minutes : 30
Seconds : 8
 

3.3 Example 3: Working with LocalTime Timezones


Is there a way to create the LocalTime with time zones? yes, we can pass the timezone to now() method.

Look at the below examples.

First, created two timezones instances from ZoneId and passed the timezone to LocalTime.now() method.
Then, next obtained the difference between two timezone dates in hours and seconds.
package com.javaprogramto.java8.dates.localtime;

import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;

public class LocalTimeCreationExample {
	public static void main(String[] args) {

		// Getting the Los Angeles id from ZoneId.
		ZoneId zoneLosAngeles = ZoneId.of("America/Los_Angeles");

		// Getting the Amsterdam id from ZoneId.
		ZoneId zoneAmsterdam = ZoneId.of("Europe/Amsterdam");

		// LocalTime object with timezone 1
		LocalTime timeLosAngeles = LocalTime.now(zoneLosAngeles);
		System.out.println("timeLosAngeles : " + timeLosAngeles);

		// LocalTime object with timezone 2
		LocalTime timeAmsterdam = LocalTime.now(zoneAmsterdam);
		System.out.println("timeAmsterdam : " + timeAmsterdam);

		// Getting the time differences between these two times in hours
		long diffInHours = ChronoUnit.HOURS.between(timeLosAngeles, timeAmsterdam);
		System.out.println("Time diff in hours : "+diffInHours);
		
		// Getting the time differences between these two times in seconds
		long diffInSeconds = ChronoUnit.SECONDS.between(timeLosAngeles, timeAmsterdam);
		System.out.println("Time diff in seconds : "+diffInSeconds);
	}
}
 
Output:
timeLosAngeles : 08:13:09.492711
timeAmsterdam : 17:13:09.495475
Time diff in hours : 9
Time diff in seconds : 32400
 

3.4 Example 4: Formatting LocalTime to String


Example program on to convert LocalTime to String value. Time pattern can be created using DateTimeFormatter.ofPattern() and pass this pattern to format() method. 
package com.javaprogramto.java8.dates.localtime;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class LocalTimeFormatExample {
	public static void main(String[] args) {

		// LocalTime object with the current time
		LocalTime currentTime = LocalTime.now();
		System.out.println("Current Time : " + currentTime);

		// converting DateTime to String in format "hh:mm:ss"
		String timeInString = currentTime.format(DateTimeFormatter.ofPattern("hh:mm:ss"));
		System.out.println("time 1 in string : " + timeInString);

		// converting DateTime to String in format "hh:mm:ss a"
		String time2InString = currentTime.format(DateTimeFormatter.ofPattern("hh:mm:ss a"));
		System.out.println("Time 2 in string : " + time2InString);
	}
}
 
Output:
Current Time : 21:59:28.682714
time 1 in string : 09:59:28
Time 2 in string : 09:59:28 PM
 

3.5 Example 5: Adding and Misusing (subtract) Time Values using LocalTime


Use plusHours(), plusMinutes() and plusSeconds() methods to plus the time values.

package com.javaprogramto.java8.dates.localtime;

import java.time.LocalTime;

public class LocalTimeAddSubtractExample {
	public static void main(String[] args) {

		// LocalTime object with the current time
		LocalTime currentTime = LocalTime.of(10,20,30);
		System.out.println("Current Time : " + currentTime);

		// Adding time to the current time
		LocalTime timeHoursAdded = currentTime.plusHours(1);
		LocalTime timeMinsAdded = currentTime.plusMinutes(10);
		LocalTime timeSecsAdded = currentTime.plusSeconds(60);

		System.out.println("timeHoursAdded : " + timeHoursAdded);
		System.out.println("timeMinsAdded : " + timeMinsAdded);
		System.out.println("timeSecsAdded : " + timeSecsAdded);
	}
}
 
Output:
Current Time : 10:20:30
timeHoursAdded : 11:20:30
timeMinsAdded : 10:30:30
timeSecsAdded : 10:21:30
 
Use minusHours(), minusMinutes() and minusSeconds() to subtract the time from LocalTime objects.
package com.javaprogramto.java8.dates.localtime;

import java.time.LocalTime;

public class LocalTimeAddSubtractExample {
	public static void main(String[] args) {

		// LocalTime object with the current time
		LocalTime currentTime = LocalTime.of(10,20,30);
		System.out.println("Current Time : " + currentTime);

		// Substracting time to the current time
		LocalTime timeHoursSubstracted = currentTime.minusHours(1);
		LocalTime timeMinsSubstracted = currentTime.minusMinutes(10);
		LocalTime timeSecsSubstracted = currentTime.minusSeconds(60);

		System.out.println("timeHoursSubstracted : " + timeHoursSubstracted);
		System.out.println("timeMinsSubstracted : " + timeMinsSubstracted);
		System.out.println("timeSecsSubstracted : " + timeSecsSubstracted);			
	}
}
 
Output:
Current Time : 10:20:30
timeHoursSubstracted : 09:20:30
timeMinsSubstracted : 10:10:30
timeSecsSubstracted : 10:19:30
 

3.6 Example 6: LocalTime until(), truncatedTo() and compareTo(), isAfter(), isBefore() Methods


package com.javaprogramto.java8.dates.localtime;

import java.time.LocalTime;
import java.time.temporal.ChronoUnit;

public class LocalTimeOtherMethodsExample {
	public static void main(String[] args) {

		// LocalTime object with the current time
		LocalTime currentTime = LocalTime.now();
		System.out.println("Current Time : " + currentTime);

		LocalTime nextTime = LocalTime.of(12, 59);
		System.out.println("next time : "+nextTime);

		// until() example - to compute the time diff.
		long hours = nextTime.until(currentTime, ChronoUnit.HOURS);
		System.out.println("untill hours : "+hours);
		
		// truncatedTo() example - to get the time limited to a specifed unit of time.
		LocalTime truncatedHours = currentTime.truncatedTo(ChronoUnit.HOURS);
		System.out.println("LocalTime truncated to hours : "+truncatedHours);
		
		// comparing times part
		int isSame = currentTime.compareTo(nextTime);
		
		if(isSame == 0) {
			System.out.println("currentTime and nextTime are same");
		} else {
			System.out.println("currentTime and nextTime are not same");
		}
	
		if(currentTime.isAfter(nextTime)) {
			System.out.println("currentTime is after nextTime");
		} else {
			System.out.println("currentTime is not after nextTime");
		}
		
		if(currentTime.isBefore(nextTime)) {
			System.out.println("currentTime is before nextTime");
		} else {
			System.out.println("currentTime is not before nextTime");
		}
		
	}
}
 
Output:
Current Time : 22:34:25.272566
next time : 12:59
untill hours : 9
LocalTime truncated to hours : 22:00
currentTime and nextTime are not same
currentTime is after nextTime
currentTime is not before nextTime
 

4. Conclusion


In this article, you've seen about the java 8 LocalTime class and its mostly used methods with examples.

GitHub:


Read Next:

Monday, November 23, 2020

How To Convert String to Date in Java 8

1. Overview


In this article, you'll be learning how to convert String to Date in Java 8 as well as with Java 8 new DateTime API.

String date conversion can be done by calling the parse() method of LocalDate, DateFormat and SimpleDateFormat classes.

LocalDate is introduced in java 8 enhancements.

DateFormat is an abstract class and direct subclass is SimpleDateFormat.

To convert a String to Date, first need to create the SimpleDateFormat or LocalDate object with the data format and next call parse() method to produce the date object with the contents of string date.

Java Convert String to Date (Java 8 LocalDate.parse() Examples)


First, let us write examples on string to date conversations with SimpleDateFormat classs and then next with DateFormat class.

At last, Finally with LocalDate class parse() method.

All of the following classes are used to define the date format of input string. Simply to create the date formats.

LocalDate
DateFormat
SimpleDateFormat

Note: In date format Captial M indicates month whereas lowercase m indicate minutes.

This will be asked in the interview or written test on How to Format Date to String in Java 8?

Java - String not equals Examples

1. Overview

In this article, You'll learn how to compare the string contents with == and does not compare with != operator.

How to fix != comparison in two ways. Read till end of this tutorial, you will get better understanding for sure.

string-does-not-equal-java

Saturday, November 21, 2020

Java 8 New Date Time API Examples

1. Overview


In this java 8 programming tutorial, we will be learning today Date-Time api is introduced in java 8. Before that first, we will see what are the drawbacks of java.util.Date api before java 8. And next, features of new Date Time api. What are the new classes introduced? Working example programs on each class and how the dates are simplified using with timezones.

Java 8 New Date Time API Examples

How To Compare Two Dates In Java and New Java 8?

1. Overview

In this article, You'll learn how to compare two dates in java and also how to compare the dates in java 8.

Dates comparison means checking whether the date 1 is after date 2 or which one is older or future date.

First let us look into the older java api in java 7 and next exploring the different options with JDK 8.

If-else condition example

2. Comparing Two Dates 

First, Let us create two Date objects in format of "yyyy-MM-dd" using SimpleDateFormat.parse() method.

Next, use compareTo() method to compare the dates. compareTo() method returns integer value. 

  • If the returned value is 0, it means both dates are same. 
  • If the value > 0 then date 1 is after date 2.
  • if the value < 0 then date 1 is before date 2.

package com.javaprogramto.java8.dates.compare;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Example program to compare two dates in java
 * 
 * @author JavaProgramTo.com
 *
 */
public class DateCompareBeforeJava8 {

	public static void main(String[] args) throws ParseException {
		// Date format
		String DATE_FORMAT = "yyyy-MM-dd";
		
		// Creating an object for SimpleDateFormat
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
		
		// Date 1 created from string using SimpleDateFormat
		Date date1 = sdf.parse("2021-01-01");

		// Date 2 created from string using SimpleDateFormat
		Date date2 = sdf.parse("2021-02-01");
		
		// comparing two dates
		int dateOrder = date1.compareTo(date2);
		
		// printing the date comparison value returned by compareTo() method
		System.out.println("Dates comparision value : "+dateOrder);
		
		// Deciding the dates order.
		if(dateOrder == 0) {
			System.out.println("Date 1 and Date 2 are equal.");
		} else if(dateOrder > 0) {
			System.out.println("Date 1 is after Date 2.");
		} else {
			System.out.println("Date 1 before Date 2");
		}
	}
}

Output:

Dates comparision value : -1
Date 1 before Date 2

In the above example code, We called date1.compareTo(date2) and it returned value -1. So, it is indicating date 1 is older than date 2. Finally, it has executed else block.

If you swap the dates the it will say date 1 is after date 2.

3. Java 8 - Comparing Two Dates

Java 8 is added with lots of new features and DateTime api is one them.

There are mainly 3 classes added in java 8 to work with dates.

  • java.time.LocalDate
  • java.time.LocalDateTime
  • java.time.ZonedDateTime

Let us try to compare the same dates using java 8 api first with examples then we will understand when to which one from above three mostly used classes.

package com.javaprogramto.java8.dates.compare;

import java.text.ParseException;
import java.time.LocalDate;

/**
 * Example program to compare two dates in java 8 with LocalDate.
 * 
 * @author JavaProgramTo.com
 *
 */
public class DateCompareInJava8 {

	public static void main(String[] args) throws ParseException {
		
		// Creating first date using LocalDate.of() method.
		LocalDate date1 = LocalDate.of(2021, 01, 01);
		
		// Creating second date using LocalDate.of() method.
		LocalDate date2 = LocalDate.of(2021, 02, 01);
		
		// comparing dates with isEqual(), isAfter() and isBefore() methods.
		boolean isEqual = date1.isEqual(date2);
		boolean isAfter = date1.isAfter(date2);
		boolean isBefore = date1.isBefore(date2);
		
		// java 8 date comparisons results
		System.out.println("Date 1 and Date 2 are equals? : "+isEqual);
		System.out.println("Date 1 is after Date 2? : "+isAfter);
		System.out.println("Date 1 is before Date 2? : "+isBefore);
		

		// comparing two dates older way with compareTo() method.
		int dateOrder = date1.compareTo(date2);
		
		// printing the date comparison value returned by compareTo() method
		System.out.println("Dates comparision value with compareTo() returned value : "+dateOrder);
		
		// Deciding the dates order.
		if(dateOrder == 0) {
			System.out.println("Date 1 and Date 2 are equal.");
		} else if(dateOrder > 0) {
			System.out.println("Date 1 is after Date 2.");
		} else {
			System.out.println("Date 1 before Date 2");
		}

	}

}

Output:

Date 1 and Date 2 are equals? : false
Date 1 is after Date 2? : false
Date 1 is before Date 2? : true
Dates comparision value with compareTo() returned value : -1
Date 1 before Date 2

In the above example, we have used LocaleDate class methods isEqual(), isAfter() and isBefore() methods to compare the dates order.

If these methods returns true means that method condition is satisfied else not met the condition.

And alos still the new api has the compareTo() method to work with the older jdk.

4. Java 8 - Comparing Two Dates Along With Time Component

In java 8, LocalDate class compares only the dates and does not consider time part in the date. Other two classes such as LocalDateTime and ZonedDateTime work with date along with time. All 3 classes have isEqual(), isAfter() and isBefore() methods for dates comparisons.

Now, look at the date and time comparisons examples using LocalDateTime and ZonedDateTime classes.

LocalDateTime Example:

package com.javaprogramto.java8.dates.compare;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * Example program to compare two dates in java 8 with LocalDateTime.
 * 
 * @author JavaProgramTo.com
 *
 */
public class DateCompareLocalDateTimeInJava8 {

	public static void main(String[] args) throws ParseException {

		// Creating first date using LocalDateTime.of() method.
		LocalDateTime datetime1 = LocalDateTime.of(2021, 02, 01, 01, 01, 01);

		// Creating second date using LocalDateTime.now() method with milliseconds.
		LocalDateTime datetime2 = LocalDateTime.now();

		// comparing dates with isEqual(), isAfter() and isBefore() methods.
		boolean isEqual = datetime1.isEqual(datetime2);
		boolean isAfter = datetime1.isAfter(datetime2);
		boolean isBefore = datetime1.isBefore(datetime2);

		// java 8 date comparisons results
		System.out.println("DateTime 1 and DateTime 2 are equals? : " + isEqual);
		System.out.println("DateTime 1 is after DateTime 2? : " + isAfter);
		System.out.println("DateTime 1 is before DateTime 2? : " + isBefore);
	}

}

Output:

DateTime 1 and DateTime 2 are equals? : false
DateTime 1 is after DateTime 2? : true
DateTime 1 is before DateTime 2? : false

ZonedDateTime Example:

package com.javaprogramto.java8.dates.compare;

import java.text.ParseException;
import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
 * Example program to compare two dates in java 8 with ZonedDateTime.
 * 
 * @author JavaProgramTo.com
 *
 */
public class DateCompareZonedDateTimeInJava8 {

	public static void main(String[] args) throws ParseException {

		// Creating first date using ZonedDateTime.of() method with nano seconds and time zone id.
		ZonedDateTime zonesDatetime1 = ZonedDateTime.of(2021, 02, 01, 01, 01, 01, 1, ZoneId.systemDefault());

		// Creating second date using ZonedDateTime.now() method with milliseconds.
		ZonedDateTime zonedDatetime2 = ZonedDateTime.now();

		// comparing dates with isEqual(), isAfter() and isBefore() methods.
		boolean isEqual = zonesDatetime1.isEqual(zonedDatetime2);
		boolean isAfter = zonesDatetime1.isAfter(zonedDatetime2);
		boolean isBefore = zonesDatetime1.isBefore(zonedDatetime2);

		// java 8 date comparisons results
		System.out.println("ZonedDateTime 1 and ZonedDateTime 2 are equals? : " + isEqual);
		System.out.println("ZonedDateTime 1 is after ZonedDateTime 2? : " + isAfter);
		System.out.println("ZonedDateTime 1 is before ZonedDateTime 2? : " + isBefore);
	}

}

Output:

ZonedDateTime 1 and ZonedDateTime 2 are equals? : false
ZonedDateTime 1 is after ZonedDateTime 2? : true
ZonedDateTime 1 is before ZonedDateTime 2? : false

5. Conclusion

In this tutorial, you've seen how to compare two dates in java 8 and older java versions and differences among java 8 date classes,

  • java.time.LocalDate
  • java.time.LocalDateTime
  • java.time.ZonedDateTime

GitHub

DateCompareBeforeJava8

DateCompareInJava8

DateCompareLocalDateTimeInJava8

DateCompareZonedDateTimeInJava8

Read Next:

java.util.Date Examples

How to use MinguoDate in java 8?

Java 8 TemporalAdjusters

Java 8 new features indepth

API:

LocalDate  LocalDateTime  ZonedDateTime