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);

                                and

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

Date and Time Keywords

KeywordDescription
Daylight SavingMost 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 YearFebruary 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 ZoneA 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.

ClassesDescription
java.util.DateThe 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. CalendarThe 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. LocaleA 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.TimeZoneTimeZone represents a time zone offset, and also figures out daylight savings.
java.sql. DateA 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. SimpleDateFormatimpleDateFormat 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. ClockA clock providing access to the current instant, date and time using a time-zone.
java.time. DurationA time-based amount of time, such as ‘43.6 seconds’.
java.time. InstantAn instantaneous point on the time-line.
java.time.LocalDateA date without a time-zone in the ISO-8601 calendar system, such as 2008-11-04.
java.time. LocalDateTimeA date-time without a time-zone in the ISO-8601 calendar system, such as 2008-12-04T11:14:30.
java.time. LocalTimeA time without a time-zone in the ISO-8601 calendar system, such as 11:14:30.
java.time. MonthDayA month-day in the ISO-8601 calendar system, such as –11-04.
java.time. OffsetDateTimeA 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.OffsetTimeA time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as 11:16:30+01:00.
java.time.PeriodA date-based amount of time in the ISO-8601 calendar system, such as ‘3 years, 2 months and 5 days’.
java.time.MonthA month-of-year, such as ‘June’.
java.time.DayOfWeekA day-of-week, such as ‘Wednesday’.
java.time.YearA year in the ISO-8601 calendar system, such as 2008.
java.time.YearMonthA year-month in the ISO-8601 calendar system, such as 2008-11.
java.time.ZoneDateTimeA 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. ZoneIdA time-zone ID, such as Europe/Paris.
java.time.   ZoneOffsetA time-zone offset from Greenwich/UTC, such as +02:00.
java.time.
DateTimeExeption
This exception is used to indicate problems while calculating with creating, querying and manipulating date-time objects.
java.time.
DateTimeParseException
This exception thrown when an error occurs during parsing and error index
java.time.
UnsupportedTemporalTypeException
This exception indicates that a ChronoField or ChronoUnit is not supported for a Temporal class.
java.time.   ZoneRulestExceptionThis 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.
java.util.Date
 

Date date=new Date();

java.util.Calendar and java.util.GregorianCalendar

Calendar calendar=Calendar.getInstance();
Calendar gCalnedar=GregorianCalendar.getInstance();

java.time.LocaleDateTime
LocalDateTime localDateTime=LocalDateTime.now();

java.time.LocaleDate
LocalDate localDate=LocalDate.now();

java.time.LocaleTime
LocalTime localTime=LocalTime.now();

Java : Current Date and Time Example

Date and Time Formatting Characters

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

LetterDate & Time ComponentPresentationExample
GEra designatorTextAD
yYearYear1998; 98
YWeek yearYear2007; 07
MMonth in year (context sensitive)MonthAugust; Aug; 08
LMonth in year (standalone form)MonthAugust; Aug; 08
wWeek in yearMonth28
WWeek in monthNumber3
DDay in yearNumber230
dDay in monthNumber18
FDay of week in monthNumber3
EDay name in weekTextTuesday;
uDay number of week (1 = Monday, …, 7 = Sunday)Number2
aAm/pm markerTextPM
HHour in day (0-23)Number21
kHour in day (1-24)Number22
KHour in am/pm (0-11)Number10
hHour in am/pm (1-12)Number5
mMinute in HourNumber34
sSecond in minuteNumber55
SMillisecondNumber578
zTime zoneGeneral time zonePacific Standard Time; PST; GMT-08:00
ZTime zoneRFC 822 time zone08td>
XTime zoneISO 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 PatternResult
EEE MMM dd hh:mm:ss zzz yyyySat Jul 28 01:35:28 PDT 2018
yyyy-MM-dd’T’HH:mm:ss.SSS zzz2018-07-28T13:35:28.245 PDT
yyyy-MM-dd’T’hh:mm:ss.SSS’Z’2018-07-28T01:35:28.
yyyy-MM-dd7/28/2018
yyyyMMdd20180728
yyyy/MM/dd7/28/
yyyy.MM.dd G ‘at’ HH:mm:ss z2001.07.04 AD at 12:08:56 PDT
EEE, MMM d, ”yyWed, Jul 4, ’01
h:mm a12:08 PM
hh ‘o”clock’ a, zzzz12 o’clock PM, Pacific Daylight Time
K:mm a, z0:08 PM, PDT
yyyyy.MMMMM.dd GGG hh:mm aaa“02001.July.04 AD 12:08 PM”
EEE, d MMM yyyy HH:mm:ss ZWed, 4 Jul 2001 12:08:56 -0700
yyMMddHHmmssZ-0700
yyyy-MM-dd’T’HH:mm:ss.SSSZ2001-07-04T12:08:56.235-0700
yyyy-MM-dd’T’HH:mm:ss.SSSXXX-07-04T12:08:56.235-07:00
YYYY-‘W’ww-u2001-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(str);
 System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date);
 System.out.printf("%s %tB %<te, %<tY&, &Due date:&, date);

Output

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

ss

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);

and

//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

Advertisements
Advertisements

Your Feedback Motivate Us

If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

Happy Learning !!!

“Learn From Others Experience"