Java Reference
In-Depth Information
4-12. Obtaining a Machine Timestamp
Problem
You need to obtain a machine-based timestamp from the system.
Solution
Utilize an Instant class, which represents the start of a nanosecond on the timeline
based on machine time. In the following example, an Instant is used to obtain the
system timestamp. The Instant is also utilized in other scenarios, such as when cal-
culating different dates based on the Instant .
public static void instants(){
Instant timestamp = Instant.now();
System.out.println("The current timestamp: "
+ timestamp);
//Now minus three days
Instant minusThree = timestamp.minus(3,
ChronoUnit.DAYS);
System.out.println("Now minus three days:"
+ minusThree);
ZonedDateTime atZone
= timestamp.atZone(ZoneId.of("GMT"));
System.out.println(atZone);
Instant yesterday = Instant.now().minus(24,
ChronoUnit.HOURS);
System.out.println("Yesterday: " + yesterday);
}
Here is the result:
The current timestamp: 2014-12-27T05:36:42.199Z
Now minus three days:2014-12-24T05:36:42.199Z
Search WWH ::




Custom Search