I just announced the new Spring Boot 2 material, coming in REST With Spring:
This quick article describes how we may get the current date, current time and current time stamp in Java 8.
2. Current Date
First, let’s use java.time.LocalDate to get the current system date:
LocalDate localDate = LocalDate.now();
To get the date in any other timezone we can use LocalDate.now(ZoneId):
LocalDate localDate = LocalDate.now(ZoneId.of("GMT+02:30"));
We can also use java.time.LocalDateTime to get an instance of LocalDate:
LocalDateTime localDateTime = LocalDateTime.now(); LocalDate localDate = localDateTime.toLocalDate();
3. Current Time
With java.time.LocalTime, let’s retrieve the current system time:
LocalTime localTime = LocalTime.now();
To get the current time in a specific time zone, we can use LocalTime.now(ZoneId):
LocalTime localTime = LocalTime.now(ZoneId.of("GMT+02:30"));
We can also use java.time.LocalDateTime to get an instance of LocalTime:
LocalDateTime localDateTime = LocalDateTime.now(); LocalTime localTime = localDateTime.toLocalTime();
4. Current Timestamp
Use java.time.Instant to get a time stamp from the Java epoch. According to the JavaDoc, “epoch-seconds are measured from the standard Java epoch of 1970-01-01T00:00:00Z, where instants after the epoch have positive values:
Instant instant = Instant.now(); long timeStampMillis = instant.toEpochMilli();
We may obtain the number of epoch-seconds seconds:
Instant instant = Instant.now(); long timeStampSeconds = instant.getEpochSecond();
In this tutorial we’ve focused using java.time.* to get the current date, time and time stamp.
As always, the code for the article is available over on Github.