javalocalizationcalendartimezonetimestamp

How do I get a UTC Timestamp from Calendar?


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);

Solution

  • 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.