Working with Date and Time API - Java 8 Feature

by
Aug 15, 2014 12:55 AM

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..
We are using class java.util.Date which is available since beginning of Java e.i. JDK 1.0 for date and time handling in Java, but this class has many problems like

1. java.util.Date class is not thread-safe and can lead to potential concurrency issues
2. object of java.util.Date class stores date and time both, so the name of class is confusing
3. this does not stores time zone information
4. poor API design which creates confusions for example year starts at 1900, month starts at 1 and days starts at 0
Date date = new Date(2001, 12, 1);
what 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.1
5. lacking of various methods like add/subtract some days to a date object
6. java.util.Date.toString() returns time-zone as well while this object does not have information about time zone

Because of above points developers started using third party API like Joda-Time

Later 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).

High level overview of JDK 1.8 Date Time API

1. a new package java.time is created
2. LocalDate class is to hold local date only without time zone information
3. LocalTime class is to hold local time
4. ZonedDateTime class to hold date and time both with time zone information

all of above class has following similarities
1. None of them have public constructor
2. None of them have setter method (immutable objects)
3. All of them have factory methods to create instances
4. All of them have most of below methods (making similar interface to each other)

methoddescription
1ofCreates an instance where the factory is primarily validating the input parameters, not converting them.
2fromConverts the input parameters to an instance of the target class, which may involve losing information from the input.
3parseParses the input string to produce an instance of the target class.
4formatUses the specified formatter to format the values in the temporal object to produce a string.
5getReturns a part of the state of the target object.
6is Queries the state of the target object.
7withReturns a copy of the target object with one element changed; this is the immutable equivalent to a set method on a JavaBean.
8plusReturns a copy of the target object with an amount of time added.
9minusReturns a copy of the target object with an amount of time subtracted.
10toConverts this object to another type.
11atCombines 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
Lambda Expressions - Java 8 Feature


comments powered by Disqus