Java 8 – Date Time API

Introduction

Java 8 comes with a much improved and much required change in the way date and time is handled. Almost all of us have experienced the pains of working with date in java. Most of us have switched to Joda Time, but java 8 has changed that with a much cleaner and more extensive API. Before we look at the API lets look at the date and time concepts. The java date follows the Gregorian Calendar rules. The classes that represent the date and time concepts are present in the java.time package. The important classes in this package are:

  • java.time.Period: This class represents the date part of the datetime. It represents the date part in terms of days, months and years. for example 1 year, 2 months and 5 days
  • java.time.Duration: This class represents the time part of the datetime. It represents the time part in terms of seconds and nanoseconds. for example ’29 seconds’
  • java.time.Instant: This represents a particular instant in the timeline. It stores the number of seconds through epoch time and also has another field that stores the nanoseconds
  • java.time.LocalDate: This stores the date part of date-time in terms of years-months-days. It does not store the TimeZone. The class is immutable.
  • java.time.LocalTime: This class stores the time part of date time without any TimeZone info.
  • java.time.LocalDateTime: This class stores the LocalDate and LocalTime but no TimeZone
  • java.time.ZonedDateTime: This class stores the LocalDateTime and the TimeZone info as a ZoneOffset object. The class has access to ZoneRules which can be used to convert to local time
  • java.time.ZoneOffset:This stores the time zone offset from UTC. The zone rules are stored in ZoneId.
  • java.time.OffsetDateTime:This stores the local datetime with the offset. This class does not have information about Zone Rules.

Lets look at examples for these, later in this tutorial we will look at ways to format and parse time.


Creating a local date

		Instant now = Instant.now();
		//2014-09-20T14:32:33.646Z

This creates a new time instant. The instant does not have timezone info. If you print the instant it prints the time with UTC time zone.


Epoch seconds

		System.out.println(now.getEpochSecond());
		// prints 1411137153
		

The epoch seconds is the number of seconds since 1970-01-01T00:00:00Z


Adding time to an Instant

		Instant tomorrow = now.plus(1,ChronoUnit.DAYS);
		// prints 2014-09-20T14:32:33.646Z
		

the plus function allows adding time intervals. The time intervals can be NANOS, MICROS, MILLIS, SECONDS, MINUTES, HOURS, HALF_DAYS, DAYS


Subtracting time from an Instant

		Instant yesterday = now.minus(1,ChronoUnit.HALF_DAYS);
		// prints 2014-09-20T03:38:33.860Z
		

The minus function allows subtracting time from an instant. It allows the same time intervals as plus.


Comparing two instants

		System.out.println(now.compareTo(tomorrow)); // prints -1
		

The compare function can be used to compare two dates. It returns -1 if the date that is passed is after , 1 if it is before


check if one instant is after another

System.out.println(now.isAfter(yesterday));// prints true

create a LocalDateTime

		LocalDateTime localDateTime = LocalDateTime.now();
		System.out.println(localDateTime); // prints 2014-09-28T13:01:40.556

Note that this gets the time in the local time zone


Convert LocalDateTime to datetime in particular zone

		System.out.println(localDateTime.atZone(ZoneId.of("America/New_York")));
		// prints 2014-09-28T13:07:31.207-04:00[America/New_York]

This creates and instance of ZonedDateTime


Get the day of week from DateTime

		System.out.println(DayOfWeek.from(localDateTime));
		// prints SUNDAY.
		// (yes, i am working on a sunday :-( )
		

Get the day of year from DateTime

		System.out.println(localDateTime.get(ChronoField.DAY_OF_YEAR));
		// prints 271
		

The other fields that can be returned are MINUTE_OF_HOUR, MINUTE_OF_DAY, HOUR_OF_AMPM, HOUR_OF_DAY, AMPM_OF_DAY, DAY_OF_WEEK, DAY_OF_MONTH, DAY_OF_YEAR, MONTH_OF_YEAR, YEAR, OFFSET_SECONDS (offset from UTC).


Get the LocalDate part of LocalDateTime

		System.out.println(localDateTime.toLocalDate());
		// prints 2014-09-29
		

Get the LocalTime part of LocalDateTime

		System.out.println(localDateTime.toLocalTime());
		// prints 22:26:30.146
		

Create a LocalDateTime from year, month, day, hour, min

		System.out.println(LocalDateTime.of(2014, 10, 1, 10, 0));
		// prints 2014-10-01T10:00
		

Create LocalDateTime by parsing a string

		LocalDateTime parsedLocalDateTime = LocalDateTime.parse("2014-01-01T11:00");
		

Create LocalDateTime in different timezone

		System.out.println(LocalDateTime.now(ZoneId.of("UTC")));
		// prints 2014-09-29T17:07:26.653 (the local timezone in UTC)
		

Create LocalDateTime from an Instant and a timezone

		Instant now = Instant.now();
		System.out.println(LocalDateTime.ofInstant(now, ZoneId.of("UTC")));
		2014-09-29T17:09:19.644
		

Create a ZonedDateTime

		ZonedDateTime zonedDateTime = ZonedDateTime.now();
		2014-09-29T22:41:24.908+05:30[Asia/Calcutta]
		

Find the difference between two times in specific units

		System.out.println(zonedDateTime.until(ZonedDateTime.parse("2014-09-29T22:41:00-10:00"), ChronoUnit.HOURS));
		// prints the difference between the current zonedDateTime and the zonedatetime parsed from the above string
		

Get the offset for the current zonedDateTime

		System.out.println(zonedDateTime.getOffset());
		// prints the offset e.g. +10:00
		

Parsing or formatting a datetime using DateTimeFormatter

		System.out.println(zonedDateTime.format(DateTimeFormatter.ofPattern("'The' dd 'day of' MMM 'in year' YYYY 'and zone is' z")));
		// prints The 29 day of Sep in year 2014 and zone is IST
		

Converting ZoneDateTime to another zone.
There are two ways to do this. In the first method, the code maintains the same instant but changes the timezone. In the second method the code just changes the timezone but the localtime is constant. Look at this example.

		System.out.println(zonedDateTime);
		System.out.println(zonedDateTime.toInstant());
		System.out.println(zonedDateTime.withZoneSameInstant(ZoneId.of("America/Chicago")));
		System.out.println(zonedDateTime.withZoneSameLocal(ZoneId.of("America/Chicago")));
		
		// prints 
		//System.out.println(zonedDateTime);
		//System.out.println(zonedDateTime.toInstant());
		//System.out.println(zonedDateTime.withZoneSameInstant(ZoneId.of("America/Chicago")));
		//System.out.println(zonedDateTime.withZoneSameLocal(ZoneId.of("America/Chicago")));
		

The above examples give some of the method present in the DateTime API. There are many other methods but this should suffice for basic usage. If you have a specific problem then do drop us a mail or put in your comments and we will be happy to answer.

Leave a Comment