14

In Java when I use Calendar.getInstance(); I get a Calendar object for the current Timezone. But java.sql.Timestamp is usually stored in UTC Time and not in local time. So how can I get the UTC Time from a Calendar instance?

    DateFormat df = DateFormat.getTimeInstance();
    Calendar cal = Calendar.getInstance();
    Timestamp time = new Timestamp(cal.getTimeInMillis());

    // Prints local time
    System.out.println(df.format(new Date(time.getTime())));

    // Printe local time, but I want UTT Time
    System.out.println("timestamp: " + time);
1
  • For new readers to the question use java.time, the modern Java date and time API. for your date and time work. DateFormat, Calendar and Timestamp all had bad design problems and have been outdated the last 10 years ( Timestamp possibly "only" since your JDBC driver was upgraded to JDBC 4.2, which should still be several years ago).
    – Anonymous
    Commented Sep 3 at 14:31

4 Answers 4

18

When you call Calendar.getTime(), that will give you a value which doesn't have a related time zone - or you could think of it as being in UTC - for the instant that the calendar represents. So if it was (say) 9am in the calendar's time zone, it could be 5pm UTC.

Now java.util.Date (and I'd imagine Timestamp) will be formatted in the system default time zone when you call toString() (whether implicitly or explicitly) - but don't let that fool you into thinking that the time zone is part of the data within the object itself.

You need to be very clear about exactly what you're trying to achieve - and then you'll probably find that Joda Time lets you express that in code more clearly than the built-in libraries do.

2
  • I actually get a Calendar instance from an API, and then I have to get the UTC Timestamp from that. I like Joda Time, but I can't use it here.
    – Jonas
    Commented Dec 7, 2010 at 13:56
  • @Jonas: Okay, in that case you just need to use getTime() - that will give you a UTC timestamp.
    – Jon Skeet
    Commented Dec 7, 2010 at 14:07
12

Your code is already doing exactly what you want. Timestamp (as well as Date) does not have timezone information and should always contain a GMT timestamp (which ist what Calendar.getTimeInMillis() returns).

The reson why you see local time printed is that the DateFormat factory methods as well as Timestamp.toString() implicitly use the system timezone.

2
  • Ok, is it any way to make DateFormat display it in GMT Time?
    – Jonas
    Commented Dec 7, 2010 at 13:58
  • @Jonas: DateFormat has a setTimeZone() method Commented Dec 7, 2010 at 14:22
6

tl;dr

Instant.now() 

Avoid legacy date-time classes

You are using troublesome old date-time classes now supplanted by the java.time classes. No need to be using DateFormat, Calendar, or Timestamp.

If you must interopt with a Calendar from old code not yet updated to java.time, convert using new methods added to the old classes. Extract an obsolete java.util.Date, and convert to Instant.

Instant instant = myCal.getTime().toInstant() ;

Using java.time

Get the current moment as an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = Instant.now() ;

2017-02-17T03:29:15.725Z

Database

With JDBC 4.2 and later, you can directly exchange a Instant object with your database. So no need for the obsolete java.sql.Timestamp.

myPreparedStatement.setObject( … , instant ) ;

And retrieval:

Instant instant = myResultSet.getObject( … , Instant.class ) ;

Count from epoch

Apparently you want a number of milliseconds since the epoch reference date of 1970-01-01T00:00:00Z. You can extract that number from an Instant. But beware of data loss, as a Instant has a resolution of nanoseconds which you will be truncating to milliseconds.

long millis = instant.toEpochMilli() ;

1487302155725


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

3

Following snippet should satisfy your requirements:

df.setTimeZone(TimeZone.getTimeZone("UTC"));
1
  • I've just formatted your answer , and didn't downvote.
    – j2ko
    Commented Feb 10, 2017 at 7:49

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.