In this article we are going to understand, how can we handle Date and Time in Java.
In the early version of Java, the 'java.util.Date' class was introduced to handle Date and Time in Java.
- This class instance represents date and time as number of the milliseconds since January 1, 1970, 00:00:00 UTC (epoch time).
- 'java.util.Date' class internally maintains milliseconds using a Long type variable. When we create a new Date(), internally it calls System.currentTimeMillis().
- 'java.util.Date' is mutable means after initialization, we can modify using methods like setTime(long time) and setHours(int hours).
This class has many issues, like
- As this is mutable, it cannot be thread-safe in a multithreaded environment and can lead to unexpected results.
- This class doesn't store information about zones, so it's very difficult to handle time in different zones and can cause inconsistent results.
- This class does not accurately represent time before January 1, 1970.
- Methods provided by this class, are ambiguous. for example
- 'getYear()' method it will return current year –1900
- 'getMonth()' method returns the month as an integer based on zero indexing. January will represent 0, February represent 1, and so on.
- Let's say we want to add 1 second in the current time, we can do like below. But again it's ambiguous.
- To format it we depend on java.text.SimpleDateFormat class, which is also mutable and not thread-safe.
To overcome challenges of java.util.Date, java.util.Calendar introduced.
- 'java.util.Calendar' provides an enhanced method to manipulate date and time, which were ambiguous and verbose in the case of 'java.util.Date'.
- 'java.util.Calendar' provides timezone support using java.util.TimeZone class. In the below example, we can see a clear difference related to the zone between 'java.util.Date' and 'java.util.Calendar'.
Despite all these enhancements, 'java.util.Calendar' also has some issues.
- It's mutable and hence it's not thread-safe in a multi-threaded environment.
- like java.util.Date, java.util.Calendar represents months as zero-based indices, which can be confusing and error-prone for developers.
- Methods of java.util.Calendar also have ambiguous names, for example
- get(int field), by just seeing method get() it becomes ambiguous to understand how can we use it, by the method name, it is not easy to find what it is doing and how we can use it. This method retrieves specific calendar field values like Calendar.MONTH, Calendar.YEAR.
- 'add(int field, int amount)', by just seeing the method it is not easy to determine how exactly we can use it and may lead to error if used wrongly. This method adds a specified amount to a calendar field.
- Both 'java.util.Date' and 'java.util.Calendar' lacks in handling Daylight saving time (DST) transition issues.
Daylight Saving Time (DST) is the practice of setting the clocks forward by one hour during the warmer months of the year to extend evening daylight and reduce the need for artificial lighting in the evenings. The clocks are typically set forward in the spring ("spring forward") and set back in the fall ("fall back"). many countries like Canada follow this tradition.
- To format it, we again depend on java.text.SimpleDateFormat class
To overcome all these Challenges Java 8 Date Time API comes into the picture.
- Java 8 introduces new classes like java.time.LocalDate, java.time.LocalTime, java.time.LocalDateTime and java. time.ZonedDateTime.
- These classes are immutable, which means once created their value cannot be changed.
- These are thread-safe.
- Provide separate classes for clear separation of concerns
- java.time.LocalDate for date only , no time no zone
- java.time.LocalTime for time only, no date no zone
- java.time.LocalDateTime for date time without zone
- java.time.ZonedDateTime for date time with zone
- Methods provided by these classes are readable and understandable by just the method name.
- Example , getYear() : to get Year
- getMonthValue(): to get Month and its 1-based indexing.
- plusDays()
- minusHours()
- Robust support for the zone using classes like java.time.ZonedDateTime, java.time.ZoneId and java.time.ZoneOffset. It also handles DST (Daylight Saving Time) without any issue.
Let's see some coding examples to understand better,
- Let's check how can we create instances of new classes.
- Let's see if it's mutable or not
- Let's see if it Thread Safe or not
- Let's see how we can perform some manipulations, operations, and formatting on it.
- Let's see if it can handle DST (Daylight saving time) or not.
Java 8 also introduced some classes like java.time.Period and java.time.Duration.
java.time.Period :
- It represents the quantity of time-based on date units (year, months, days).
- Useful for calculating differences or duration between dates that don't involve specific time.
- It is immutable and thread-safe.
- It only works with LocalDate.
java.time.Duration :
- It represents a quantity of time based on time units (seconds, nanoseconds).
- Useful for calculating time differences or duration involving specific times.
- It's also immutable and thread-safe.
- It doesn't work with LocalDate but does work with LocalTime, LocalDateTime, and ZonedDateTime.
Note : Please comment below for any improvement , suggestions, regarding any wrong information present in this article. We will improve it so that only right information available in this article.

Nice Article!!!
ReplyDelete