6

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.

5
  • That's the formatter. You need to format it yourself not let the toString method do it for you! Dec 27, 2015 at 20:58
  • @BoristheSpider Thanks for the reply. Sorry I am not sure how to do that? Dec 27, 2015 at 20:59
  • Start from the top and work your way down... Dec 27, 2015 at 21:01
  • It is the Date#toString() method which uses the system time zone (which the operating system is using), when it is displayed, not Date itself. It by default and always takes UTC. So, if you persist a Date instance to an underlying database, it should be according to UTC. Those answers merely say how to display Date Time, for example, on the Java console which do not take into account that you need to persist a Date instance into a database (where the Java 8 DataTime is not supported as of now).
    – Tiny
    Dec 27, 2015 at 21:28
  • Possible duplicate of Format Instant to String Jul 19, 2017 at 6:56

5 Answers 5

8
System.out.println("DATETIME = " + utc.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
7
  • 1
  • you can add zone-id or anything else you need inside pattern
    – LowLevel
    Dec 27, 2015 at 21:06
  • 1
    Wrong pattern ("h" instead of "H" was used), hence wrong answer which was unfortunately accepted without close check if the produced results are correct or not. Furthermore, any subsecond parts are suppressed - why? Oct 17, 2019 at 8:52
  • @Meno Hochschild. DateTimeFormatter.ofPattern was the reason why the answer has been accepted. It is the function the Topicstarter has been looking for. Thank you for your comment. I have edited the hour format.
    – LowLevel
    Oct 18, 2019 at 9:10
  • Fortunately, life is not that difficult to make unfortunate things out of non-unfortunate things. Just be a little bit tolerant and creative. And everything will be okay.
    – LowLevel
    Oct 18, 2019 at 9:12
7

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.

2
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));
-3
        private Calendar getUTCTime(){
            Calendar calendar = Calendar.getInstance();
            // Assuming your time is in utc + 8
            calendar.add(Calendar.HOUR, -8);
            return calendar;
        }
2
  • Question says UTC, and a the desired output is a String
    – Chisko
    Jul 19, 2017 at 6:38
  • Thank you for this code snippet, which may provide some immediate help. A proper explanation would greatly improve its educational value by showing why this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. Jul 19, 2017 at 12:08
-5

I suggest you to use Joda-Time.

DateTime dt = new DateTime(DateTimeZone.UTC);
1
  • 7
    The OP is obviously using Java 8, why would you recommend using Joda Time when the new Data/Time API is perfectly capable of formatting dates. Dec 27, 2015 at 21:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.