markthegrea
markthegrea

Reputation: 3861

How do I set a Java Calendar to a specific UTC time?

When I do this:

Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.set(9999, 11, 31, 0, 0, 0);
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yy HH.mm.ss.SSSSSSSSS a");
String date = formatter.format(c.getTime());
assertEquals("31-Dec-99 00.00.00.000000000 AM", date);

I get this: 30-Dec-99 18.00.00.000000318 PM

How do I get the time I want?

Upvotes: 0

Views: 1479

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1504122

You're creating a SimpleDateFormatter without specifying the time zone - so it will use the system local time zone by default. If you want the formatter to use UTC as well, simply set it.

Note that a Date value is time zone agnostic - it's just the number of milliseconds since the Unix epoch. It has no idea what time zone was originally used to create it. That's why you need to call setTimeZone on the formatter (or use a constructor which takes a zone).

The 318 in the milliseconds shows that your original Date value contains a milliseconds component of 318. A java.util.Date only supports a resolution of milliseconds anyway, so you should use SSS000000 in your format... and you should set the millisecond value to 0 anyway:

c.set(Calendar.MILLISECOND, 0);

(Annoyingly, setting "year, month, day, hour, minute, second" doesn't reset the millisecond value. Seems crazy to me, but...)

As a side note, the built-in Java date/time API is pretty grim in various ways. You may well want to look into using Joda Time instead...

Upvotes: 0

BalusC
BalusC

Reputation: 1109874

You need to set the formatter's time zone as well before performing the format.

formatter.setTimeZone(c.getTimeZone());

Otherwise it will use the platform default time zone.


Unrelated to the concrete problem, the calendar doesn't hold nano seconds, so that part may still be a bit off after formatting.

Upvotes: 3

Related Questions