Skip to content

Instantly share code, notes, and snippets.

@gauravkukade
Created May 15, 2021 11:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gauravkukade/f490a87ced1aa63c076bbe6bd7860a2c to your computer and use it in GitHub Desktop.
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/
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