Reputation: 73
So I am trying to get the current UTC time in Java ( I'm using Java 7 with ThreeTenAbp ). I have tried the following calls and all of them return the time in UTC + 12 hours which is not the real UTC time as I have checked online through various source that provide current UTC time.
Instant.now().atZone(ZoneId.of("UTC")).toString();
Instant.now().toString();
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
I don't know why these are reporting the wrong UTC time given that I'm explicitly specifying the UTC timezone, except for the second one. I also think it's unlikely that all of these methods of getting the UTC time yield the wrong result so I am wondering what I am doing wrong.
Upvotes: 1
Views: 4889
Reputation: 103
When you print Instant.now().toString()
, are you sure the result is not in UTC? Because Instant
always works in UTC.
The only thing I can guess is that you're printing the java.util.Date
directly, and this class has a terrible toString()
method which takes the JVM default timezone.
Maybe if you edit your question and add the inputs and outputs for each case, we can help you better. Because I can't reproduce your problem.
By the way, the current UTC time is (when I tested the code) 2018-03-08T14:47:08.886Z
(14:47, or 02:27 PM). If your problem is to print the time in AM/PM format, then you could use a DateTimeFormatter
:
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'hh:mm:ssaX");
String formatted = ZonedDateTime.now(ZoneOffset.UTC).format(fmt);
Using hh
gives you the hour in AM/PM (1 to 12), instead of 0 to 23 (which is the default, and also the value returned by HH
pattern). I also added a
, which gives you AM or PM, to not make the output ambiguous.
Upvotes: 0
Reputation: 86399
While I cannot be sure, of course, the very likely reason for the behaviour you have observed is that you are running your program on a computer or a device the clock of which is set incorrectly. Both Instant.now()
and new Date()
pick up the time from the system clock, so this would explain nicely.
You may object and ask: How could I set the system clock 12 hours ahead? How could I not discover? While there could be many explanations for this, the two obvious ones are:
Instant.now()
and new Date()
to give the incorrect results you observed.Upvotes: 1