【问题标题】:How to convert date and time from one time zone to another in when GMT format is given in android在android中给出GMT格式时如何将日期和时间从一个时区转换为另一个时区
【发布时间】:2015-08-25 10:28:46
【问题描述】:

我有一个 +10:00 GMT(澳大利亚/墨尔本)的特定日期和时间,它来自 google api,格式如下:-

2015-05-12T14:00:00.000+10:00

现在,我想根据设备当前时区转换上述时间。

例如:-

以上时间+5:30 GMT(印度)应该是2015-05-12 9:30:00

我怎样才能实现它?

我下面的代码是:-

    SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    sourceFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    Date parsed = null;
    try {
        parsed = sourceFormat.parse("2015-05-12 14:00:00");
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } // => Date is in UTC now

    TimeZone tz = TimeZone.getTimeZone(TimeZone.getDefault().getID());
    SimpleDateFormat destFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    destFormat.setTimeZone(tz);

    String result = destFormat.format(parsed);

    System.out.println(result);

但结果是 2015-05-12 19:30 这是错误的..

【问题讨论】:

    标签: android timezone


    【解决方案1】:

    this我认为你对getTimeZone("GMT")有误

    您应该使用getTimeZone("GMT+10:00"));,因为 GMT 是 +/-0:00

    看看我发布的文档 :)

    【讨论】:

      【解决方案2】:

      请试试这个,它在这里工作

       try {
      
      
      SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT+10"));
      
      //Local time zone
      SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      
      //Time in GMT
      String date = dateFormatLocal.format(dateFormatGmt.parse("2015-05-12 14:00:00"));
      LogUtil.LOGD(Constants.ACTIVITY_TAG, "Date- " + date);
      }catch (ParseException e) {
        e.printStackTrace();
      }
      

      【讨论】:

        【解决方案3】:

        您还可以使用Joda library 让生活更轻松。

        private String showTimeStringExample(String timeStamp) {
            //timestamp = "2015-05-12T14:00:00.000+10:00"
        
            // use Joda to parse the time stamp and convert it to java
            final Date date = ISODateTimeFormat.dateTimeParser().parseDateTime(timeStamp).toDate();
        
            // use the format you had in your question, setting the locale to the device's default
            SimpleDateFormat destFormat = new SimpleDateFormat(
                    "yyyy-MM-dd HH:mm:ss",
                    getResources().getConfiguration().locale
            );
        
            // comes out as "2015-05-12 05:00:00 in the UK
            return destFormat.format(date);
        }
        

        Gradle 依赖:

        compile 'joda-time:joda-time:2.3'
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-23
          • 2010-11-26
          • 2015-11-05
          • 2019-04-14
          相关资源
          最近更新 更多