Working with Date and Time API - Java 8 Feature

7902 Mar 20, 2016

A new java.time package is introduced in Java SE 8 for date and time handling. Let us try to understand that what are new features and why a separate API was required for date and time handling..

java.util.Date



Date date = new Date(2001, 12, 1);



High level overview of JDK 1.8 Date Time API

java.time

method description 1 of Creates an instance where the factory is primarily validating the input parameters, not converting them. 2 from Converts the input parameters to an instance of the target class, which may involve losing information from the input. 3 parse Parses the input string to produce an instance of the target class. 4 format Uses the specified formatter to format the values in the temporal object to produce a string. 5 get Returns a part of the state of the target object. 6 is Queries the state of the target object. 7 with Returns a copy of the target object with one element changed; this is the immutable equivalent to a set method on a JavaBean. 8 plus Returns a copy of the target object with an amount of time added. 9 minus Returns a copy of the target object with an amount of time subtracted. 10 to Converts this object to another type. 11 at Combines this object with another.

Working with LocalDate



package com.groupkt.java8;



import java.time.DayOfWeek;

import java.time.LocalDate;

import java.time.Month;

import java.time.temporal.TemporalAdjusters;



public class LocalDateTest {



public static void main(String[] args) {

// current date in local time zone

LocalDate date = LocalDate.now();

System.out.printf("date=[%s]%n", date); // 2014-08-15



// specific date

date = LocalDate.of(2014, Month.AUGUST, 15);

System.out.printf("date=[%s]%n", date); // 2014-08-15



// date from nth day of year

date = LocalDate.ofYearDay(2014, 227);

System.out.printf("date=[%s]%n", date); // 2014-08-15



// date from string

date = LocalDate.parse("2014-08-15");

System.out.printf("date=[%s]%n", date); // 2014-08-15



date = LocalDate.now();

//date=2014-08-15 isLeapYear=false

System.out.printf("date=%s isLeapYear=%b%n", date, date.isLeapYear());



//date=2014-08-15 number of days in this month=31

System.out.printf("date=%s number of days in this month=%d%n", date,date.lengthOfMonth());



//date=2014-08-15 number of days in this year=365

System.out.printf("date=%s number of days in this year=%d%n", date,date.lengthOfYear());



//today is [2014-08-15], yesterday was [2014-08-14] and tomorrow will be [2014-08-16]

System.out.printf("today is [%s], yesterday was [%s] and tomorrow will be [%s]%n",

date, date.minusDays(1), date.plusDays(1));



//Last day of current month=SUNDAY

System.out.printf("Last day of current month=%s%n",

date.with(TemporalAdjusters.lastDayOfMonth()).getDayOfWeek());



//Next Friday will be on 2014-08-22

System.out.printf("Next Friday will be on %s%n",

date.with(TemporalAdjusters.next(DayOfWeek.FRIDAY)));

}

}



Working with LocalTime



package com.groupkt.java8;



import java.time.LocalTime;

import java.time.temporal.ChronoUnit;



public class LocalTimeTest {



public static void main(String[] args) {

// current time

LocalTime time = LocalTime.now();

System.out.printf("time=[%s]%n", time); // 02:43:00.833



// specific time

time = LocalTime.of(13, 30);

System.out.printf("time=[%s]%n", time); // 13:30



// time from string

time = LocalTime.parse("13:30");

System.out.printf("time=[%s]%n", time); // 13:30



time = LocalTime.now();



//Current time is [02:43:00.990], before 35 minutes was [02:08:00.990] and after 35 minutes will be [03:18:00.990]

System.out.printf("Current time is [%s], before 35 minutes was [%s] and after 35 minutes will be [%s]%n",

time, time.minusMinutes(35), time.plusMinutes(35));



//truncating seconds and milliseconds time=02:45

System.out.printf("truncating seconds and milliseconds time=%s%n",

time.truncatedTo(ChronoUnit.MINUTES));



}

}



Related Links

Please enable JavaScript to view the comments powered by Disqus.

Disqus

We are using classwhich is available since beginning of Java e.i. JDK 1.0 for date and time handling in Java, but this class has many problems like1. java.util.Date class is not thread-safe and can lead to potential concurrency issues2. object of java.util.Date class stores date and time both, so the name of class is confusing3. this does not stores time zone information4. poor API design which creates confusions for example year starts at 1900, month starts at 1 and days starts at 0what do you think, date object holds "December 1, 2001" ? NO, this date object holds "January 01, 3902". This is because of confusing Date APIs, later Java team realize that this Date constructor is confusing so they deprecated it in JDK 1.15. lacking of various methods like add/subtract some days to a date object6. java.util.Date.toString() returns time-zone as well while this object does not have information about time zoneBecause of above points developers started using third party API like Joda-TimeLater Oracle team decided to have its own API for date and time handling and worked under JSR 310 with the author of Joda-Time (Stephen Colebourne).1. a new packageis created2. LocalDate class is to hold local date only without time zone information3. LocalTime class is to hold local time4. ZonedDateTime class to hold date and time both with time zone informationall of above class has following similarities1. None of them have public constructor2. None of them have setter method (immutable objects)3. All of them have factory methods to create instances4. All of them have most of below methods (making similar interface to each other)