【问题标题】:Android timezone issue, confusedAndroid时区问题,困惑
【发布时间】:2016-06-21 09:27:20
【问题描述】:

我有一个这样的日期 Tue Jun 21 14:47:37 GMT+05:30 2016 ,这是我自己创建的。我使用日历创建它。用户选择一个日期,我将其保存为日历中的毫秒数。 当我发送它时,发送它,我再次创建一个日历实例,将保存的毫秒放入其中并获取如下日期:

Calendar calendar = Calendar.getInstance();
    calendar.setTimeZone(TimeZone.getDefault());
    calendar.setTimeInMillis(SSPreferences.getDate());

现在从日历中获取日期时,我会这样做:

calendar.getTime()//This is what I send to server.

我将它发送到服务器,但是当服务器向我发送日期时,它总是比我的时间早 5.5 小时。

我知道我的时间是 GMT+5:50。那么服务器在做什么呢? 如何发送日期,以便我返回发送到服务器的相同日期。

感谢任何帮助。 谢谢

【问题讨论】:

  • 获取 UTC 时间并保持在服务器或毫秒中
  • "这是我发送到服务器的内容。" - 如何将其发送到服务器?
  • 如何将日期发送到服务器?您是否使用 httpurlconnection 将其发送到 php 脚本?还有什么?
  • @JonSkeet -- calendar.getTime()
  • 只是调用calendar.getTime() 不会向服务器发送任何内容。 你如何将它发送到服务器 - 服务器用它做什么?您如何从服务器接收价值?你得到什么毫秒值?这里缺少很多信息。

标签: android timezone datetimeoffset


【解决方案1】:

检查一下

static final String DATEFORMAT = "yyyy-MM-dd HH:mm:ss"

public static Date GetUTCdatetimeAsDate()
{
    //note: doesn't check for null
    return StringDateToDate(GetUTCdatetimeAsString());
}

public static String GetUTCdatetimeAsString()
{
    final SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    final String utcTime = sdf.format(new Date());

    return utcTime;
}

public static Date StringDateToDate(String StrDate)
{
    Date dateToReturn = null;
    SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMAT);

    try
    {
        dateToReturn = (Date)dateFormat.parse(StrDate);
    }
    catch (ParseException e)
    {
        e.printStackTrace();
    }

    return dateToReturn;
}

【讨论】:

    【解决方案2】:

    最后我通过从本地时区添加/减去 rawOffSet 解决了这个问题。

        TimeZone timeZone = TimeZone.getDefault();
        int offset = timeZone.getOffset(SSPreferences.getDate());
        WriteLog.Print("offset is "+offset);
        long newtime = SSPreferences.getDate() + offset;
        calendar.setTimeInMillis(newtime);
    

    【讨论】:

      猜你喜欢
      • 2011-01-16
      • 1970-01-01
      • 1970-01-01
      • 2011-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多