current-date-time-and-timestamp-in-java-8
Get the Current Date, Time and Timestamp in Java 8
1. Introduction
2. Current 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
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();
5. Conclusion
As always, the code for the article is available over on GitHub.