I would like to convert a Date from my current TimeZone to UTC.

The results are not understandable for me.

Code:

public static String convertToUTC(String dateStr) throws ParseException
{

    Log.i("myDateFunctions", "the input param is:"+dateStr);

    String uTCDateStr;


    Date pickedDate = stringToDate(dateStr, "yyyy-MM-dd HH:mm:ss");

    Log.i("myDateFunctions", "the input param after it is converted to Date:"+pickedDate);


    TimeZone tz = TimeZone.getDefault();
    Date now = new Date();
    Log.i("myDateFunctions:", "my current Timezone:"+tz.getDisplayName()+" +"+(tz.getOffset(now.getTime()) / 3600000));

    // Convert to UTC
    SimpleDateFormat converter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    converter.setTimeZone(TimeZone.getTimeZone("UTC"));
    uTCDateStr = converter.format(pickedDate);

    Log.i("myDateFunctions", "the output, after i converted to UTC timezone:"+uTCDateStr);

    return uTCDateStr;

}

And LogCat results are:

03-29 20:31:46.804: I/myDateFunctions(18413): the input param is:2014-04-29 20:00:00
03-29 20:31:47.005: I/myDateFunctions(18413): the input param after it is converted to Date:Tue Apr 29 20:00:00 CEST 2014
03-29 20:31:47.005: I/myDateFunctions:(18413): my current Timezone:Central European Time +1
03-29 20:31:47.005: I/myDateFunctions(18413): the output, after i converted to UTC timezone:2014-04-29 18:00:00

As you can see: My TimeZone is CET (GMT+1)

Then why if my input is 20:00 i get back 18:00 instead of 19:00 ?

有帮助吗?

解决方案

The problem is daylight savings time. UTC doesn't have it, if yours does it will increase the difference by 1 hour during part of the year.

其他提示

The answer by Game Sechan appears to be correct.

I just want to show how much easier this work is when using Joda-Time or java.time rather than the notoriously troublesome java.util.Date and .Calendar classes.

Joda-Time

In Joda-Time 2.4.

String inputRaw = "2014-04-29 20:00:00";
String input = inputRaw.replace( " ", "T" );
DateTimeZone timeZoneIntendedByString = DateTimeZone.forID( "America/Montreal" ); // Or DateTimeZone.getDefault();
DateTime dateTime = new DateTime( input, timeZoneIntendedByString );
DateTime dateTimeUtc = dateTime.withZone( DateTimeZone.UTC ); // Adjust time zones, but still same moment in history of the Universe.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top