我想将一个日期从我的当前时区转换为UTC。
我不能理解这个结果。
代码: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;
}
和LogCat结果如下:
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
可以看到:我的时区是CET (GMT+1)
那么为什么如果我的输入是20:00,我得到18:00而不是19:00 ?
问题在于夏令时。UTC没有夏令时,如果你的时区有夏令时,它会在一年中部分时间将时差增加1小时。
Game Sechan的答案似乎是正确的。
我只是想展示使用jdbc - time或java时这项工作是多么容易。而不是众所周知的麻烦的java.util.Date和. calendar类。
<标题> Joda-Time h1> 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.
标题>