简体   繁体   English

Android版本,回到夏令时会错吗?

[英]Android date, will it be wrong when going back to summer time?

This date was sent from my app looking like this: 该日期是从我的应用发送的,如下所示:

2014-10-29 09:00:17

The database stores it like this: 数据库按如下方式存储它:

Wed Oct 29 2014 09:00:17 GMT+0100 (CET)

I'm getting a date back from my server looking like the this: 我从服务器获取日期,如下所示:

2014-10-29T08:00:17.000Z (one our less)

Then I'm converting it to a calendar date like this: 然后,我将其转换为像这样的日历日期:

public static long getUTCToMillis(String time) {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
    sdf.setTimeZone(TimeZone.getTimeZone("CET")); 
    try {
        cal.setTime(sdf.parse(time));
        return cal.getTimeInMillis();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return -1;
}

This always sets the hour to 08:00 but I want it to be converted back to 09:00 like it was saved. 这始终将小时设置为08:00,但我希望像保存时一样将其转换回09:00。 If I put timezone to UTC I get 09:00 but how will that work when summer time starts again? 如果我将时区设为UTC,我会得到09:00,但是当夏季时间再次开始时,它将如何工作? How can I get this to display the correct time? 我怎样才能显示正确的时间?

Take a look at TimeZone.getOffset(long time) 看一下TimeZone.getOffset(长时间)

The method returns the time difference between UTC and your target timezone. 该方法返回UTC与您的目标时区之间的时差。

So you can do something like this: 因此,您可以执行以下操作:

public static long getUTCToMillis(String time) {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());

    TimeZone timezone = TimeZone.getTimeZone("CET");

    try {
        Date date = sdf.parse(time);
        long offSet = timezone.getOffset(date.getTime());
        cal.setTime(date);
        cal.add(Calendar.MILLISECOND, offset);
        return cal.getTimeInMillis();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return -1;
}

As a side note, I suggest you store time values in UTC regardless of where your user is. 附带说明一下,我建议无论用户身在何处,都将时间值存储在UTC中。 For example, if your application is used in two different time zones simultaneously, the server should store the same value. 例如,如果您的应用程序同时在两个不同的时区中使用,则服务器应存储相同的值。 Time conversion will and should be done locally on user's device based on the time zone he/she is in. 时间转换将并且应该根据用户所在的时区在用户设备上本地完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM