Java Code Examples: DateTime
java.util.Date
is in core java API since Java 1.0. And it is not recommended for use. If you are using Java 8 or a later version, it is better to use java.time.LocalDate
and java.time.Instant
, which were introduced in Java 8.
In this post, I will cover common operations related to datetime.
Get current datetime
Instant
Instant now = Instant.now(); // Capture the current moment in UTC, with a resolution of nanoseconds. Returns a `Instant` object. |
ZonedDateTime
ZonedDateTime zonedDateTime = ZonedDateTime.now(); |
LocalDateTime
LocalDateTime localDateTime = LocalDateTime.now(); |
java.util.Date
Date date = new Date(); |
Format and parse datetime
Instant
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") |
ZonedDateTime
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") |
LocalDateTime
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); |
java.util.Date
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); |
Extract information from a datetime
LocalDate
LocalDate localDate = LocalDate.now(); |
java.util.Date
Date date = new Date(); |