New long-awaited Java 8 became the main newsmaker of this spring in the world of programming. A lot of articles are already written about main changes: lambda expressions, functional interfaces and Streams collections.

But apart of these very important changes there are also some new API added in new version of Java, that won’t change language appearance, but may become very useful in some cases.

Date-Time API is one of such innovations, that is used to deal with time and date and is intended to replace not very successful java.util.Date и java.util.Calendar.

In order to see the differences between java.util.Calendar and java.time lets have a look at one example. We will set the date 1 January 2014 (midnight) and derive to console the date that will be in 90 days in the format "dd/MM/yyyy HH:mm:ss".

java.util.Calendar:

Calendar calendar = Calendar.getInstance(); calendar.set(2014, Calendar.JANUARY, 1, 0, 0, 0); SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); calendar.add(Calendar.DAY_OF_MONTH, 90); System.out.println(dateFormat.format(calendar.getTime()));

Date-Time API:

LocalDateTime date = LocalDateTime.of(2014, 1, 1, 0, 0, 0, 0); DateTimeFormatter format = DateTimeFormatter .ofPattern("dd/MM/yyyy HH:mm:ss"); System.out.println(date.plusDays(90).format(format));

Widespread library Joda-Time (for comparison):

DateTime dateTime = new DateTime(2014, 1, 1, 0, 0, 0, 0); System.out.println(dateTime.plusDays(90) .toString("dd/MM/yyyy HH:mm:ss"));

As you can see even from such simple example, Date-Time API allows us to execute operations with time and date more easily and gracefully. It’s also important that objectes created by java.time are immutable, and therefore thread-safe unlike classes from java.util. Moreover, date indication starts from 1 (JANUARY, MONDAY) in java.time, not from 0 like in Calendar.

The similarity between the Date-Time API and Joda-Time is not accidental, as Joda-Time became spiritual progenitor of "JSR 310: Date and Time API" - most of the concepts were borrowed directly, but despite that there are some differences that do not allow us to consider Joda-Time reference implementation of JSR 310.

What is included in Date-Time API?

java.time

Core of Date-Time API. Includes base classes for working with time, date, and time intervals. Date presentation format used in these classes is based on ISO-8601 (international standard based on the Gregorian calendar, example of time and date: 2005-08-09T18: 31:42).

java.time.chrono

API for working with calendars other than ISO-8601 (Hijrah, ThaiBuddhist, Minguo etc.). As well as abstract classes and interfaces for creating your own calendars.

java.time.format

Formatting and parsing dates and times.

java.time.temporal

Advanced API for programmers writing their own libraries, and frameworks.

java.time.zone

Classes for working with time zones.

Main class methods in java.time

A number of agreements on the method names was implemented in Date-Time API for the purpose of convenience and easy readability. It should be noted that due to the fact that most object classes in java.time are immutable, the usual method set () is not used. Instead, a number of methods that take object as a parameter and return a new object with the specified values are implemented. The names / name prefixes of most commonly used methods of the library are listed below.

now()

Returns object, that includes current date/time. Example:

LocalDate date = LocalDate.now(); System.out.println(date); LocalTime time = LocalTime.now(); System.out.println(time); ------------ 2014-03-30 18:28:10.852

of()

Static factory, that creates object with specific values, the values of the input parameters are validated, but not converted. In case of incorrect input data – shows DateTimeException. Example:

LocalDate date = LocalDate.of(2014, Month.MARCH, 20); System.out.println(date);

from()

One more static factory, converts the input data to the target class object. Example:

LocalDate date = LocalDate.from(LocalDateTime.now());

parse()

As the name suggests, this method takes as input a string, trying to parse it and create an object. Example:

LocalTime time = LocalTime.parse("10:15:30");

format()

Returns the values as a string. String format is determined by formatter sent to the method. Example:

LocalDateTime date = LocalDateTime.now(); DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"); System.out.println(date.format(format)); --------- 30/03/2014 18:44:06

get...

Standart getter-method, that returns the value of the object. Example:

LocalDateTime date = LocalDateTime.now(); System.out.println(date.getDayOfMonth()); System.out.println(date.getDayOfYear()); ------------ 30 89

is...

Methods that queries the state of the target object (true/false). Example:

LocalDate currentDate = LocalDate.now(); LocalDate april1 = LocalDate.of(2014, Month.APRIL, 1); System.out.println(currentDate.isBefore(april1));

with…

Returns copy of sent object with one changed value, in fact this method is analogue of set methods. Example:

LocalDate currentDate = LocalDate.now(); LocalDate nextYear = currentDate.withYear(2015); System.out.println(nextYear); -------- 2015-03-30

plus…

Returns copy of the object with the date/time increased on set value. Example:

LocalDate currentDate = LocalDate.now(); LocalDate nextYear = currentDate.plusYears(1); System.out.println(nextYear); -------- 2015-03-30

minus…

Returns copy of the object with the date/time reduced on set value. Example:

LocalDate currentDate = LocalDate.now(); LocalDate prevDate = currentDate.minusMonths(2); System.out.println(prevDate); -------- 2014-01-30

to…

Converts object from one type to another. Example:

LocalTime currentTime= LocalTime.now(); System.out.println(currentTime.toSecondOfDay()); ------ 68215

Main classes in Date-Time API

The library uses two approaches of the representation of time, firstly human familiar format (human time): year, month, day, hour, minute, second. Secondly machine representation of time (machine time), based on the concept of epoch (Epoch - some date from which time begins) and the interval in nanoseconds measured from that date. Let's look at the most frequently used classes in Date-Time API.

Classes for work with date

LocalDate

Represents data in format year-month-date, doesn’t include time and time zone. Example:

LocalDate date = LocalDate.of(2014, Month.MARCH, 20); System.out.println(date); ----------- 2014-03-20

YearMonth

Represents month of specific year. Also there is method lengthOfMonth() showing number of days in the month. Example:

YearMonth feb2014 = YearMonth.of(2014, Month.FEBRUARY); System.out.printf("%s: %d%n", feb2014, feb2014.lengthOfMonth()); YearMonth feb2016 = YearMonth.of(2016, Month.FEBRUARY); System.out.printf("%s: %d%n", feb2016, feb2016.lengthOfMonth()); ----------- 2014-02: 28 2016-02: 29

MonthDay

Represents day of specific month. Example:

MonthDay monthDay = MonthDay.of(Month.MARCH, 29); System.out.println(monthDay); ----------- 3-29

Year

Represents year, together with method isLeap allows to know whether the specific year is leap year. Example:

Year year2014 = Year.of(2014); Year year2016 = Year.of(2016); System.out.printf("%s: %b%n", year2014, year2014.isLeap()); System.out.printf("%s: %b%n", year2016, year2016.isLeap()); ------------ 2014: false 2016: true

DayOfWeek

Enum, that includes days of the week from 1 (MONDAY) to 7(SUNDAY). Method getDisplayName(textStyle, locale) allows to get day of the week in different formats depending on set locale. Example:

DayOfWeek dow = DayOfWeek.SUNDAY; Locale locale = Locale.ENGLISH; System.out.println(dow.getDisplayName(TextStyle.FULL, locale)); System.out.println(dow.getDisplayName(TextStyle.NARROW, locale)); System.out.println(dow.getDisplayName(TextStyle.SHORT, locale)); locale = Locale.GERMAN; System.out.println(dow.getDisplayName(TextStyle.FULL, locale)); ---------- Sunday S Sun Sonntag

Month

Enum, that includes months from 1 (JANUARY ) to 12 (DECEMBER). The same as DayOfWeek has method getDisplayName(textStyle, locale). Example:

Month month = Month.MARCH; Locale locale = Locale.ENGLISH; System.out.println(month.getDisplayName(TextStyle.FULL, locale)); locale = Locale.FRANCE; System.out.println(month.getDisplayName(TextStyle.FULL, locale)); ------------ March mars

Classes for work with time

LocalTime

Class to represent time in human familiar format: hours, minutes, seconds. Example:

LocalTime time = LocalTime.of(7, 45, 28); System.out.println(time); --------- 07:45:28

LocalDateTime

Includes as date (year-month-date) and also time (hours: minutes: seconds). Example:

LocalDateTime dateTime = LocalDateTime.of(2014, Month.APRIL, 4, 17, 7, 56); System.out.println(dateTime); ------------ 2014-04-04T17:07:56

Instant

Moment of time. In fact, represents how many nanoseconds passed from epoch beginning. (1970-01-01T00:00:00Z). May be used for creating timestamps, instead of System.nanoTime() и System.currentTimeMillis(). Example:

Instant timestamp1 = Instant.now(); long nanos = System.nanoTime(); Instant timestamp2 = Instant.now().plusMillis(1000); System.out.println(timestamp1); System.out.println(nanos); System.out.println(timestamp2); ------------- 2014-03-30T14:16:40.809Z 15436821524120 2014-03-30T14:16:41.810Z

In this article we review only the basic classes of java.time. There are also tools for working with time zones (java.time.zone), work with non-standard calendars (java.time.chrono) and much more.

In general, the Date and Time API is a powerful and convenient tool to work with dates and time, it is a decent substitute for out-of-date classes of java.util.Date and java.util.GregorianCalendar