Before jump into Date and Time API, you should aware of two concepts called time zones and daylight saving. Because some applications are required time very accurately. For example, let’s think about what will happen if a flight booking site uses its local time to insert the records into the database.
The time zone — is a geographical area that follows the same time. The time is adopted for all social, commercial, and legal activities within that time zone. All-time zones are computed using the Greenwich Observatory in England as a starting point.
The universal time standard (UTC) — is a standard used to set all-time zones around the world. According to this standard, all the time zones have a particular UTC offset.
Daylight Saving Time (DST) — is the practice of setting the clocks forward one hour from standard time during the summer months, and back again in the fall, in order to make better use of natural daylight.
Actually, this article not about topics like time zones, universal time standards, and daylight saving. You should know these things as common senses. But as a programmer, you need to give more attention to these concepts when you are dealing with time.
Time affects your application in two ways.
- If the application should maintain the correct time with respect to time zones. Ex:- Flight ticket booking system
- If the application should maintain time periods. Ex:- Medicine reminder
In the first example, the user deals with their local time. As a programmer, we must write the program to convert it to UTC and save it in the database. When the user retrieves a record, we have to convert UTC to their local time.
In the second example, the UTC doesn't matter. We need to maintain the time period. Assume your application uses the local time on the user's mobile phone. If he flies to another country and changes the time of his mobile phone, his medicine routine goes wrong.
Let’s see how to handle date and time in Java. Before Java 8, the Date and Time API is a little bit confusing topic. Because the old version has several issues as follows.
- Date class exists in two different packages (java.util, java.sql)
- Date/Calendar classes are not thread-safe
- Hard to deal with timezones
- Cannot format the date and time without using java.text package
Date and Time API in Java 8
Since Java 8, a new Date and Time API has been introduced. Date and Time classes are included in java.time package as follows.
The LocalDate represents only the date in ISO format (yyyy-MM-dd). It has a private constructor. So this class provides
LocalDate.now() method to create an instance with the system’s current date information. And we can get the LocalDate representing a specific day by using the
LocalDate.of(yyyy,MM,dd) method. Also, you can pass s specific date as a string in the
LocalDate today = LocalDate.now(); //date on local machine
LocalDate christmasDay = LoacalDate.of(2021, 12, 25); //specific day
LocalDate birth = LoacalDate.parse("1997-12-31"); //specific day
There are some other methods to change the value of the
Using methods like
LocalDate tomorrow = today.plus(1);
LocalDate twoMonths = today.plusMonths(2);//same date after 2 months
LocalDate threeMonths = today.plus(3, ChronoUnit.MONTHS);
The LocalTime represents only the time. This class also similar to the previous one. You can create an instance for all three methods (
LocalTime time = LocalTime.now(); //time on local machine
LocalTime lunchTime = LoacalDate.of(12, 30, 00); //specific time
Localtime meetingTime = LoacalDate.parse("16:30");
And there are plus, minus methods as well,
LocalTime plusHour = time.plusHours(1);
LocalTime minusMins = time.minusMinutes(30);
Different getter methods are available to get specific units of time (hour, min, and secs)
int hour = LocalTime.parse("16:30").getHour();
isBefore() method for comparing two LocalTime instances,
boolean isbefore = LocalTime.parse("04:30").isBefore(LocalTime.parse("08:30"));
This can be considered as a combination of LocalDate and LocalTime classes. All the above methods are available here.
.parse() — to create an instance
plusMinutes() , etc — to change the instance value
getminutes() , etc — to get specific units
As our previous examples, we understand the importance of dealing with time-zone-specific date and time. Here is the solution from Date and Time API.
ZoneId — An identifier used to represent different zones. There are about 40 different time zones. For example, ZoneId of Sri Lanka is ‘Asia/Colombo’.
The LocalDateTime can be converted to a specific zone,
ZoneId zoneId = ZoneId.of("UTC/Greenwich");ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
OffsetDateTime class and OffsetTime class
In ZonedDateTime class, you need to find the corresponding zoneId. With OffsetDateTime and OffserTime classes, you can use offset in the ISO-8601 calendar system. For example, 2021–05–16T10:15:30+01:00 means the offset is +01.00 from GMT/UTC.
ZoneOffset zoneOffSet = ZoneOffset.of("+05:30");
OffsetTime time = OffsetTime.now(zoneOffSet); //only time
OffsetDateTime date = OffsetDateTime.now(zoneOffSet);//date and time
Period class and Duration class
First, we need to understand the difference between Period class and Duration class. The Period class works with dates while the Duration class works with the time.
Using the Period class,
LocalDate initialDate = LocalDate.parse("2021-05-15");
LocalDate dueDate= initialDate.plus(Period.ofDays(5));//2021-05-20
The Period class has various getter methods such as
getDays() to get values from a Period object.
int days = Period.between(initialDate, dueDate).getDays();
Using the Duration class,
LocalTime initialTime = LocalTime.of(9, 30, 0);
LocalTime dueTime = initialTime.plus(Duration.ofHours(2));
The Period class also has various getter methods.
int hours = Duration.between(initialTime, dueTime).getHours();
In this article, I explain few classes in Date and Time API. This is not the whole content of this API. I hope this will be helpful if you are a beginner. If I missed any points, let me know your suggestion in the comment section.
Learn more about Date and Time API from the Oracle website.