【问题标题】:Convert from current TimeZone to UTC decrement by 2 hours instead of 1从当前时区转换为 UTC 递减 2 小时而不是 1
【发布时间】:2014-05-09 06:35:09
【问题描述】:

我想将日期从我当前的时区转换为 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 呢?

【问题讨论】:

  • 您的时区有夏令时吗?如果是这样,那可能会增加 1 小时的转换时间(UTC 不会)。
  • 我总是徘徊为什么 stackoverflw 中的 ppl 害怕给出答案。也许是因为反对票?嗯,你是对的。请写下这个答案,以便我接受。
  • 我在猜测时使用评论,因此查看列表的人不会认为它已被回答。

标签: android datetime datetimeoffset android-date java-time


【解决方案1】:

问题在于夏令时。 UTC 没有它,如果你有,它会在一年中的部分时间增加 1 小时的差异。

【讨论】:

    【解决方案2】:

    answer by Game Sechan 似乎是正确的。

    我只想展示使用 Joda-Time 或 java.time 比使用臭名昭著的麻烦 java.util.Date 和 .Calendar 类时这项工作容易得多。

    乔达时间

    Joda-Time2.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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      • 2012-11-17
      相关资源
      最近更新 更多