Question

I use DateTimeZone.convertLocalToUTC to convert local time to UTC. The time is changed correctly, but after conversion, the timezone info still says the Original local timezone. Please refer below sample code

Date gmttime = new Date(tz.convertLocalToUTC(System.currentTimeMillis(),false));
System.out.println(gmttime.toString());

Output : Wed Oct 16 12:58:19 IST 2013

Please note the bold value, I expected it to be UTC . Please let me know if I am missing something.

Was it helpful?

Solution

#Date.toString() will print the date in the local timezone.

Use SimpleDateFormat to print the Date formatted for a specific TimeZone:

public static void main(String[] args) {
    Date date = new Date();
    SimpleDateFormat format = new SimpleDateFormat("E MMM  dd HH:mm:ss:SS z");
    format.setTimeZone(TimeZone.getTimeZone("UTC"));
    System.out.println(format.format(date));
}

OTHER TIPS

Try:

final Date date = new Date();
final String ISO_FORMAT = "E MMM dd HH:mm:ss zzz yyyy";
final SimpleDateFormat sdf = new SimpleDateFormat(ISO_FORMAT);
final TimeZone utc = TimeZone.getTimeZone("UTC");
sdf.setTimeZone(utc);
System.out.println(sdf.format(date));

Output:

Wed Oct 16 08:53:50 UTC 2013

convertLocalToUTC Converts a local instant to a standard UTC instant with the same local time. http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTimeZone.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top