Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java get UTC time

I want to get the time in UTC time zone. So I wrote the code:

import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Date;

public class RegularSandbox {

    public static void main(String[] args) {

        ZonedDateTime utc = ZonedDateTime.now(ZoneOffset.UTC);

        System.out.println("DATETIME = " + Date.from(utc.toInstant()));

    }
}

The problem is the output shows me the time in PST (my local timezone). I need it to output the time in UTC so I can store it inside of my databases.

like image 904
user2924127 Avatar asked Dec 27 '15 20:12

user2924127


3 Answers

System.out.println("DATETIME = " + utc.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
like image 121
LowLevel Avatar answered Oct 14 '22 07:10

LowLevel


You do too much when trying to convert to old java.util.Date. And then you implicitly use its method toString() which should be well known for the observed behaviour to print the instant always in your system timezone.

But printing in UTC timezone is extremely simple, not even a formatter is needed if you can cope with ISO-8601-notation:

ZonedDateTime utc = ZonedDateTime.now(ZoneOffset.UTC);

System.out.println("DATETIME = " + utc.toInstant());
// output: DATETIME = 2015-12-30T15:01:18.483Z (Instant is always printed with UTC offset)

System.out.println("DATETIME = " + utc);
// output: DATETIME = 2015-12-30T15:01:57.611Z (the same because you 
// have explicitly set the UTC Offset when constructing the ZonedDateTime)

You see, the behaviour of toString() of the new Java-8 classes Instant and ZonedDateTime is much clearer and is always in ISO-format. No need for a confusing conversion to Date.

About specialized formatters, you will only need one if you intend to deviate from ISO-8601-format - maybe using localized month names or extra printing of weekdays etc. Example in US-style:

System.out.println(
  "DATETIME = " 
  + utc.format(DateTimeFormatter.ofPattern("MM/dd/uuuu h:mm:ss a xxx")));
// output: DATETIME = 12/30/2015 3:14:50 PM +00:00

Note that the answer of @LowLevel uses a wrong pattern. If you leave out the symbol a (AM/PM-marker) then you should not choose the half-day-hour-symbol h but H (24-hour-format). And the timezone or offset symbol (here x) is crucial because otherwise the printed datetime will not be automatically recognized as being in UTC timezone.

like image 32
Meno Hochschild Avatar answered Oct 14 '22 06:10

Meno Hochschild


ZonedDateTime utc = ZonedDateTime.now(ZoneOffset.UTC);
final SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z"); // you can specify format that you want to get
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("UTC time: " + sdf.format(utc));
like image 2
m.aibin Avatar answered Oct 14 '22 06:10

m.aibin