Created
May 15, 2021 11:19
-
-
Save gauravkukade/f490a87ced1aa63c076bbe6bd7860a2c to your computer and use it in GitHub Desktop.
A java program to get current date time using the java.time.Instant class. Check the blog post at https://coderolls.com/get-current-date-time-in-java/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.time.Instant; | |
import java.time.LocalDateTime; | |
import java.time.ZoneId; | |
import java.time.format.DateTimeFormatter; | |
/** | |
* A java program to get current date time using the java.time.Instant class | |
* @author Gaurav Kukade at coderolls.com | |
*/ | |
public class InstantExample { | |
public static void main(String[] args) { | |
Instant instant = Instant.now(); | |
// print instant object | |
System.out.println(instant); // 2021-05-15T10:11:45.331237189Z | |
// get epoch time in milliseconds | |
// epoch timestamp is number of milliseconds/seconds since January 1, 1970, 00:00:00 GMT | |
System.out.println(instant.toEpochMilli()); // 1621073505331 | |
// get epoch time in seconds | |
System.out.println(instant.getEpochSecond()); // 1621073505 | |
// we can convert instant to LocalDateTime, LocalDate, LocalTime | |
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"); | |
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); | |
System.out.println(dateTimeFormatter.format(localDateTime)); // 15/05/2021 15:41:45 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment