Java 8 Instant (Timestamp) example.
The LocalDateTime, ZonedDateTime and other classes are representing date in human readable formats. Java 8 introduced
Instant class to represent machine readable time formats.
This class models a single instantaneous point on the time-line. This might be used to record event time-stamps in the application.
The range of an instant requires the storage of a number larger than a long. To achieve this, the class stores a long representing epoch-seconds and an int representing nanosecond-of-second, which will always be between 0 and 999,999,999. The epoch-seconds are measured from the standard Java epoch of 1970-01-01T00:00:00Z where instants after the epoch have positive values, and earlier instants have negative values. For both the epoch-second and nanosecond parts, a larger value is always later on the time-line than a smaller value.
InstantTsEx |
package com.java2novice.datetime;
import java.time.Instant;
public class InstantTsEx {
public static void main(String[] args) {
// current time in timestamp format
Instant currTimeStamp = Instant.now();
System.out.println("current timestamp: "+currTimeStamp);
// get current time in milli seconds
System.out.println("current time in milli seconds: "+currTimeStamp.toEpochMilli());
// get current time in unix time
System.out.println("current time in unix time: "+currTimeStamp.getEpochSecond());
//parsing date from ISO 8601
Instant strToDate = Instant.parse("2015-11-01T12:00:00Z");
System.out.println("string to date conversion: "+strToDate);
}
}
|
|