JB Header
Java 8 - How to get current timestamp using java.time.Instant
This quick coding tip shows how to get current timestamp in Java 8 using java.time.Instant instance and then convert it to the desired timezone with the help of an example. Java 8 code for getting the machine timestamp
Java 8 code for getting the system timestamp
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class MachineTimestamp {
  public static void main(String args[]){
    //To get machine timestamp which is returned in UTC
    Instant machineTimestamp = Instant.now();
    System.out.println("The current machine timestamp in UTC:" + machineTimestamp);
	
    //Convert the timestamp in UTC into time in required timezone
    ZonedDateTime TimeinLA = machineTimestamp.atZone(ZoneId.of("America/Los_Angeles"));
    System.out.println("Current time in Pacific Standard Time:"+TimeinLA);
  }
}
 OUTPUT of the above code
The current machine timestamp in UTC:2016-08-21T14:51:26.902Z
Current time in Pacific Standard Time:2016-08-21T07:51:26.902-07:00[America/Los_Angeles]
Quick explanation of the above code
  • In the above example, the static method java.time.Instant.now() makes a call to the System clock to get the current machine timestamp in UTC time. The now() method returns an instance of Instant itself.
  • To see the timestamp in your time zone, you can invoke the atZone() method on an Instant object.
  • The atZone() method needs a java.time.ZoneId instance to be passed to it as parameter. The ZoneId instance can be created using the method ZoneId.of(). This method takes input as a String parameter which represents the time zone ID. Given below is a table which shows the String values which can be passed to the zoneId.of() method for each of the popularly used time zone acronyms. In the above code I have used the "America/Los_Angeles" String for PST time zone.
  • If you want to use the Time Zone acronym itself then you can use the following code instead for ZoneId.of() method call - ZoneId.of(ZoneId.SHORT_IDS.get("PST"))
Table: Values to use for time zones
Time Zone String values to be passed to ZoneId.of() method
(Region Based Zone ID)
ACT Australia/Darwin
AET Australia/Sydney
AGT America/Argentina/Buenos_Aires
ART Africa/Cairo
AST America/Anchorage
BET America/Sao_Paulo
BST Asia/Dhaka
CAT Africa/Harare
CST America/Chicago
CTT Asia/Shanghai
EAT Africa/Addis_Ababa
ECT Europe/Paris
IET America/Indiana/Indianapolis
IST Asia/Kolkata
JST Asia/Tokyo
MIT Pacific/Apia
NET Asia/Yerevan
NST Pacific/Auckland
PLT Asia/Karachi
PNT America/Phoenix
PRT America/Puerto_Rico/td>
PST America/Los_Angeles
SST Pacific/Guadalcanal
VST Asia/Ho_Chi_Minh