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.

user2924127
  • 6,034
  • 16
  • 78
  • 136
  • That's the formatter. You need to format it yourself not let the `toString` method do it for you! – Boris the Spider Dec 27 '15 at 20:58
  • @BoristheSpider Thanks for the reply. Sorry I am not sure how to do that? – user2924127 Dec 27 '15 at 20:59
  • Start from [the top](http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html) and work your way down... – Boris the Spider Dec 27 '15 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 '15 at 21:28
  • Possible duplicate of [Format Instant to String](https://stackoverflow.com/questions/25229124/format-instant-to-string) – Olivier Grégoire Jul 19 '17 at 06:56

5 Answers5

8
System.out.println("DATETIME = " + utc.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
LowLevel
  • 1,085
  • 1
  • 13
  • 34
  • 1
    https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html – LowLevel Dec 27 '15 at 21:06
  • you can add zone-id or anything else you need inside pattern – LowLevel Dec 27 '15 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? – Meno Hochschild Oct 17 '19 at 08: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 '19 at 09: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 '19 at 09:12
  • By a little (more) creative I mean: if you try to be a little creative, you become a little chaotic. It helps you to become less rigid;) Believe me or believe Ofman's Core Quality Quadrant. And be happy. – LowLevel Oct 18 '19 at 09:21
  • Okay, now I have upvoted your answer (since it is correct now). – Meno Hochschild Oct 18 '19 at 10:08
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.

Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
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));
m.aibin
  • 3,528
  • 4
  • 28
  • 47
-3
        private Calendar getUTCTime(){
            Calendar calendar = Calendar.getInstance();
            // Assuming your time is in utc + 8
            calendar.add(Calendar.HOUR, -8);
            return calendar;
        }
Naresh
  • 1
  • Question says UTC, and a the desired output is a String – Chisko Jul 19 '17 at 06:38
  • Thank you for this code snippet, which may provide some immediate help. A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) 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. – Toby Speight Jul 19 '17 at 12:08
-5

I suggest you to use Joda-Time.

DateTime dt = new DateTime(DateTimeZone.UTC);
jjurm
  • 501
  • 6
  • 11
  • 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. – Boris the Spider Dec 27 '15 at 21:00