Java: Date and Time Tutorial

Date and Time handling is very common issue facing by developers while developing an application . It occurs in every layer of application like front-end , business logic and back-end etc. Mainly when interacting with different component or interacting with other back-end application for example front-end to business layer, business layer to database, database to business layer, one application to other application.

Some of application are used by international level from multiple countries and each country have different Time Zone. Some of Countries having Day Light savings also. Also know to handle Leap Year.

In this tutorial, You will learn about java date and time packages, classes and apis. Here almost  covered all type of  java date and time issues and  different situation. You will also learn in depth knowledge of Java 8 new packages, classes and apis examples and compare with legacy versions of java , Lacking of Date and Time packages before Java 8.

Topic Covered

    • Why Java 8 introduce new  package for Date and Time?
    • Date and Time Keywords
    • Date and Time packages and classes
      • Introduction of Date and Time classes.
      • Legacy to Java 8 Date Time Interoperability
    • Current Date and Time
    • Date and Time Formatting
        • Date and Time Formatting Characters
        • Date and Time Pattern Examples
      • Date and Time Formatting by java.text.SimpleDateFormat
      • Date and Time formatting by printf
      • Parsing String to Date
    • Date and Time Internationalization (TimeZone and Day Light Saving)
    • Handle JDBC Date and Time
      • Convert java.util.Date and java.sql.Date
      • Convert java.util.Date and java.sql.Timestamp
    • Convert java.util.Date to java.util.Calendar
    • Convert Java.util.Date to java.time.LocaleDateTime
    • Calculate Duration and Period
    • Date Sorting
    • System Time and calculate duration
    • Date and Time Issues Solutions

Legacy Java( Before java 8)  use mainly java.util.Date, java.util.Calendar, java.util.GregorianCalendar and java.text.SimpleDateFormat to handle Date and Time creation, operation and formatting handling.  Legacy  Java Date and Calendar Classes having lack of documents and some more issues related to time-zone, type-safe and day-light saving etc. In Java 8 added a separate package as java.time  specifically for Date and Time handling  which considered all the earlier issues Date and Calendar and added so many new classes with good documentation for API.

Why Java 8 introduce new  package for Date and Time?

Below are some issues with Legacy Date classes that’s why in Java 8 introduces new package java.time solve all existing issues.

  • 99% of Date is deprecated. Now Instant replaces java.util.Date.
  • Date’s Year is offset from 1900. Now Years have same numbering in java.time, 2018 is the year 2018.
  • Date’s Month is zero-indexed while day is one-indexed. Now Months have same numbering in java.time, 1-12 for January-December. Even better, the Month enum provides objects to represent each month of the year rather than a integer number. So you get valid values, type-safety, and self-documenting code.
  • Dates are mutable. Now virtually all of java.time classes is immutable.
  • ZonedDateTime replaces java.util.Calendar.  Except you really have to use a GregorianCalendar, ZonedDateTime replaces java.util.GregorianCalendar too.
  • Do a significant percent of developers want to use a different calendar?
    Yes. Other calendaring systems are used by many people around the globe. The java.time framework provides for this via the Chronology interface and AbstractChronology class. The default chronology is IsoChronology following the ISO 8601 standard used generally in the West. In Java 8 & 9, other bundled chronologies include Thai Buddhist, Hijrah (Islamic), Minguo (Taiwan), and Japanese Imperial.
  • Calendar.getTime() returns a Date. Just use Instant as your basic building-block class in java.time, always representing a moment in UTC with a resolution of nanoseconds. The other types such as OffsetDateTime & ZonedDateTime can convert back-and-forth with Instant.
  • There’s no Date math (like how far apart are two dates in years)
    The java.time classes have many convenient plus/minus methods. Furthermore, java.time provides powerful TemporalAduster implementations as well as enabling you to write your own. Also look to the ChronoUnit::between method, such as ChronoUnit.YEARS.between( thisLocalDate , that LocalDate ).
  • Messing with milliseconds since epoch doesn’t count
    Look to Instant::toEpochMilli and Instant.ofEpochMilli if you must use count-from-epoch, but certainly not advisable. Better to use java.time objects and ISO 8601 strings to represent date-time values.
  • JDBC date and Timestamp exchange:  JDBC driver compliant with JDBC 4.2 or later (JSR 221), you can avoid the date-time related java.sql classes such as java.sql.Date, java.sql.Timestamp classes. Those old classes are related to the troublesome old legacy classes, and are no longer needed. for Example to set and get property from database by JDBC

preparedStatement.setObject(…, instant);


                                Instant instant = resultSet.getObject( … , Instant.class ) ;

Date and Time Keywords

Keyword Description
Daylight Saving Most of the United States practice of advancing clock during summer month in order to leverage an additional hour of natural light(saving heating power, illumination power, enhancing the mood, and so on).
Leap Year February 29 is a date that usually occurs every four years, and is called leap day. This day is added to the calendar in leap years as a corrective measure, because the Earth does not orbit the sun in precisely 365 days.
Time Zone A time zone is a region of the globe that observes a uniform standard time.Time zones on land are offset from Coordinated Universal Time (UTC) by a whole number of hours (UTC−12 to UTC+14).Some higher

Date and Time packages and classes

Below are all the JAVA classes which are used to handle all type problems related Date and Time , exceptions, and formatting.

Java Date and Time Use Packages and Classes Hierarchy
Java Date and Time Use Packages and Classes Hierarchy

Introduction of Date and Time classes.

Classes Description
java.util.Date The Date class instant in time, with millisecond precision. It allowed the interpretation of dates as year, month, day, hour, minute, and second values. It also allowed the formatting and parsing of date strings.
java.util. Calendar The Calendar class is an abstract class that provides methods for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next week. An instant in time can be represented by a millisecond value that is an offset from the Epoch, January 1, 1970 00:00:00.000 GMT (Gregorian).
java.util. GregorianCalendar “GregorianCalendar is a concrete subclass of Calendar.
GregorianCalendar supports both the Julian and Gregorian calendar systems with the support of a single discontinuity, which corresponds by default to the Gregorian date when the Gregorian calendar was instituted (October 15, 1582 in some countries, later in others). “
java.util. Locale A Locale object represents a specific geographical, political, or cultural region.For example, displaying a date is a locale-sensitive operation— the number should be formatted according to the customs and conventions of the user’s native country, region, or culture.
java.util.TimeZone TimeZone represents a time zone offset, and also figures out daylight savings.
java.sql. Date A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT. ate instance must be ‘normalized’ by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.
java.text. SimpleDateFormat impleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date → text), parsing (text → date), and normalization.

After Java 8+ version

java.time. Clock A clock providing access to the current instant, date and time using a time-zone.
java.time. Duration A time-based amount of time, such as ‘43.6 seconds’.
java.time. Instant An instantaneous point on the time-line.
java.time.LocalDate A date without a time-zone in the ISO-8601 calendar system, such as 2008-11-04.
java.time. LocalDateTime A date-time without a time-zone in the ISO-8601 calendar system, such as 2008-12-04T11:14:30.
java.time. LocalTime A time without a time-zone in the ISO-8601 calendar system, such as 11:14:30.
java.time. MonthDay A month-day in the ISO-8601 calendar system, such as –11-04.
java.time. OffsetDateTime A date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as 2008-11-03T10:15:30+01:00.
java.time.OffsetTime A time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as 11:16:30+01:00.
java.time.Period A date-based amount of time in the ISO-8601 calendar system, such as ‘3 years, 2 months and 5 days’.
java.time.Month A month-of-year, such as ‘June’.
java.time.DayOfWeek A day-of-week, such as ‘Wednesday’.
java.time.Year A year in the ISO-8601 calendar system, such as 2008.
java.time.YearMonth A year-month in the ISO-8601 calendar system, such as 2008-11.
java.time.ZoneDateTime A date-time with a time-zone in the ISO-8601 calendar system, such as 2008-12-05T10:15:30+01:00 Europe/Paris.
java.time. ZoneId A time-zone ID, such as Europe/Paris.
java.time.   ZoneOffset A time-zone offset from Greenwich/UTC, such as +02:00.
This exception is used to indicate problems while calculating with creating, querying and manipulating date-time objects.
This exception thrown when an error occurs during parsing and error index
This exception indicates that a ChronoField or ChronoUnit is not supported for a Temporal class.
java.time.   ZoneRulestException This exception is used to indicate a problems with the configured time-zone rules.

In above detail you learn about package, classes for Legacy system and also after Java 8. Now here you will learn about implementation of different cases.

Legacy to Java 8 Date Time Interoperability

In Java 8 added some new methods with Legacy java.util Date and Time classes to convert object of java.time classes to get advantage new java 8 Date and Time classes with minimal changes. Below are ways of inter-operability :

java.util.Date to an java.time.Instant Conversion

Date date=new Date();
Instant instant=date.toInstant();

An java.time.Instant to java.util.Date Conversion

Date date=Date.from(instant);

java.util.Calendar to an java.time.Instant Conversion

Calendar cal=Calendar.getInstance();
Instant instant=cal.toInstant();

java.util.GregorianCalendar instance to an java.time.ZoneDateTime Conversion

Calendar gCal=GregorianCalendar.getInstance();
ZoneDateTime zoneDateTime=ZoneDateTime.ofInstant(gCal.toInstant(),ZoneId.systemDefault());

java.time.ZoneDateTime instance to java.util.GregorianCalendar

GregorianCalendar gCal=GregorianCalendar.from(zoneDateTime);

java.util.TimeZone object to java.time.ZoneId

Calendar gCal1=GregorianCalendar.getInstance();
TimeZone tz = cal.getTimeZone();
ZoneId zoneID=tz.toZoneId();
int tzoffset = cal.get(Calendar.ZONE_OFFSET);

Follow below link to know more about it and complete example.

Complete Example for Java Legacy to Java 8 Date Time Interoperability

Current Date and Time

Here are ways to get current date and time by using legacy java 8 version.
 Date date=new Date();

java.util.Calendar and java.util.GregorianCalendar
Calendar calendar=Calendar.getInstance();
Calendar gCalnedar=GregorianCalendar.getInstance();




Java : Current Date and Time Example

Date and Time Formatting Characters

Below are date and formatting characters use for formatting date and time.

Letter Date & Time Component Presentation Example
G Era designator Text AD
y Year Year 1998; 98
Y Week year Year 2007; 07
M Month in year (context sensitive) Month August; Aug; 08
L Month in year (standalone form) Month August; Aug; 08
w Week in year Month 28
W Week in month Number 3
D Day in year Number 230
d Day in month Number 18
F Day of week in month Number 3
E Day name in week Text Tuesday;
u Day number of week (1 = Monday, …, 7 = Sunday) Number 2
a Am/pm marker Text PM
H Hour in day (0-23) Number 21
k Hour in day (1-24) Number 22
K Hour in am/pm (0-11) Number 10
h Hour in am/pm (1-12) Number 5
m Minute in Hour Number 34
s Second in minute Number 55
S Millisecond Number 578
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone 08td>
X Time zone ISO 8601 time zone -08; -0800; -08:

Date and Time Pattern Examples

Below are some patterns use by organization standard based on above formatting characters.

Date & Time Pattern Result
EEE MMM dd hh:mm:ss zzz yyyy Sat Jul 28 01:35:28 PDT 2018
yyyy-MM-dd’T’HH:mm:ss.SSS zzz 2018-07-28T13:35:28.245 PDT
yyyy-MM-dd’T’hh:mm:ss.SSS’Z’ 2018-07-28T01:35:28.
yyyy-MM-dd 7/28/2018
yyyyMMdd 20180728
yyyy/MM/dd 7/28/
yyyy.MM.dd G ‘at’ HH:mm:ss z 2001.07.04 AD at 12:08:56 PDT
EEE, MMM d, ”yy Wed, Jul 4, ’01
h:mm a 12:08 PM
hh ‘o”clock’ a, zzzz 12 o’clock PM, Pacific Daylight Time
K:mm a, z 0:08 PM, PDT
yyyyy.MMMMM.dd GGG hh:mm aaa “02001.July.04 AD 12:08 PM”
EEE, d MMM yyyy HH:mm:ss Z Wed, 4 Jul 2001 12:08:56 -0700
yyMMddHHmmssZ -0700
yyyy-MM-dd’T’HH:mm:ss.SSSZ 2001-07-04T12:08:56.235-0700
yyyy-MM-dd’T’HH:mm:ss.SSSXXX -07-04T12:08:56.235-07:00
YYYY-‘W’ww-u 2001-W27-3

Date and Time formatting by printf

Java Date and time designing should be possible effortlessly utilizing printf method by  utilizing a two-letter organize, beginning with t and completion in one of the letters of the table as appeared in the accompanying code. You can check complete list of designing characters as above in “Date and Time Formatting Characters”.

For Example:

 Date date = new Date();
 String str = String.format("Current Date/Time : %tc", date );
 System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date);
 System.out.printf("%s %tB %<te, %<tY", "Due date:", date);


Current Date/Time : Mon Aug 06 11:23:05 IST 2018 Due date: August 06, 2018Due date: August 6, 2018

Follow below link to see complete example and more detail on printf for date formatting.

Parsing String to Date


Date and Time Internationalization (TimeZone and Daylight Saving Time)

For detail information and handling Daylight savings time (DST) and different time zones follow below links.

JAVA : Daylight Saving Time (DST) Handling

Java : How to convert GMT, CST, IST and PST timezone?

Handle JDBC Date and Time

JDBC databases not support java.util.Date format because it’s having time information also. For storing data in database we have to convert Java date to java.sql.Date or java.sql.Timestamp. java.sql.Timestamp is subclass of java.util.Date. Follow below below link to know more about java.sql.Date and java.sql.Timestamp  conversion.

After Java 8

Now JDBC driver compliant with JDBC 4.2 or later (JSR 221), you can avoid the date-time related java.sql classes such as java.sql.Date, java.sql.Timestamp classes. Now these legacy classes are no longer needed. for Example:

//To set property in database

preparedStatement.setObject(…, instant);


//To get property from database

Instant instant = resultSet.getObject( … , Instant.class ) ;

Calculate Duration and Period

Almost every developer handle Duration and Period issues while need to do any calculation based on Date and Time. In Java 8 introduces new classes to handle Duration and period.

  • Period : A date period is measured in days, months, and years. Period can be calculated by java.time.Period class.
  • Duration: A time duration is measured in hours, minutes, and seconds. Duration can be calculated by java.time.Duration class.

Period period= Period.between(localDate1, localDate2);

Duration duration=Duration.between(localTime1, localTime2);

Duration.toString() method return duration as P1Y10M6D. Here duration is 1 year, 10 month and 6 days.

Period.toString() method return period as PT3H10M40S. Here duration is 3 hour, 10 minute and 40 seconds.

Follow below link  to complete example of Duration and Period.

Date and Time Sorting

Basically, a list can be sorted if only all of its elements are mutually comparable by implementing the Comparable interface. If a class implements the Comparable interface, it is considered as having natural ordering which allows objects of that class to be sorted by the Collections.sort(list) method.

All basic data type wrapper classes in Java have natural ordering: String, Character, Byte, Date, Integer, Float, etc. In Java 8 classes LocalDateTime, LocalDate and LocalTime also implements comparable  interface.

Problem occurred when date in String format and following different format pattern as dd/MM/yyyy or MM/dd/yyyy ‘@’hh:mm a or some more patterns. In below examples you will see sorting of date and Time in text format and objects also.

System Time and calculate process time

System.currentTimeMillis(): Returns the current time in milliseconds. The granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.

System.nanoTime():  Returns the current value of the running Java Virtual Machine’s high-resolution time source, in nanoseconds. This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.

These methods are used to calculate processing time or performance of operations , methods and apis.

Check below example to calculate processing time :

Date and Time Issues Solutions

Sample Programs

“Learn From Others Experience"

%d bloggers like this: