Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Java’s handling of time started very early in my career, but I hadn’t yet learned the complexities and pitfalls. Most recent projects involve overseas users by default, and time zones are especially important, especially since daylight saving time complicates the process. In the ancient days of Java, there were three sets of processing times:
- Date
- Calendar
- SimpleDateFormat
Date Date = new Date() It is also understandable that many companies will not be able to expand their business scope overseas for a while, and only store basic fields such as creation and update time, so naturally there is no need to update and iterate. But when it comes to time zone transitions, Date objects can be tricky to handle. Because Date itself does not store any time zone information, even if you find some way to set it in the source code that looks like a time zone, most of it will fail.
On the other hand, time comparison and addition and subtraction are not implemented by a useful API. Prior to Java 8, you usually had to write your own utility classes. Calendar objects are used to process the year, month, day, hour, minute and second respectively:
Another problem is formatting the output, which is relatively simple:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Copy the code
Here patten can be defined in many forms.
Since the release of Automatic Java 8, LocalDateTime and ZonedDateTime have been added to handle regular dates and time zone dates, respectively. To get a feel for its handy API:
LocalDateTime now = LocalDateTime.now();// Get the current time
/ / 3 hours later
LocalDateTime localDateTime1 = now.plusHours(3);
/ / 3 minutes ago
LocalDateTime localDateTime2 = now.minusMinutes(3);
// Next year today
LocalDateTime localDateTime3 = now.plusYears(1);
// Last year today
LocalDateTime localDateTime4 = now.minusYears(1);
// Time comparison
localDateTime1.isAfter(localDateTime2);
Copy the code
It’s a fool’s errand, no more complex transformations to write, and you can focus on the implementation of the business without this distraction.
Looking at the handling of time zones, we need to introduce a time zone object: ZoneId
// Get the current time of the Chinese time zone
ZonedDateTime time = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
// Convert localDateTime to timezone
ZonedDateTime la = localDateTime.atZone(ZoneId.of("America/Los_Angeles"));
// Convert between two time zones
ZonedDateTime la = time.atZone(ZoneId.of("Asia/Shanghai")).withZoneSameInstant(ZoneId.of("America/Los_Angeles"));
Copy the code
It’s that simple.