Ignoring DST when using Java Calendars

拈花ヽ惹草 提交于 2019-12-06 01:30:33

Thanks for the answers guys, they helped me get my head around the problem. It sort of comes down to the fact that I use both the Calendar object, for presentation and storage of data, and the epoch for temporal calculations.

It turns out that the Calendar set() methods will take into account DST as a matter of course. So when I parse the time values in the text boxes that the user enters, and use set() for each individual Calendar field, the Calendar object will know, based-off historical data, whether the date you've just set will have DST applied. Because of this, it understands that you meant, for example, GMT+1, even if you didn't realise it (because, frankly, who does?!).

However, when you do getTimeInMillis(), the epoch returned has no concept of time zones or DST, so to match with the current time zone you have to apply DST manually to the returned epoch, if it applies. Conversely, when you use setTimeInMillis() on a Calendar object, it is assumed that the time you entered is GMT+0, but if the epoch is a date that currently has DST applied, the Calendar object will add it on for you, meaning you're +1 hour from where you thought you were. To solve this problem, you need to subtract DST, again if necessary, from the epoch before setting it in the calendar.

All of this confusion is particularly important on day boundaries, especially if you're using day resolution for anything, like me.

If I understand you correctly you need to parse 25/07/13 22:00 as GMT date/time:

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm");
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    Date date = sdf.parse("25/07/13 22:00");

and make a Calendar based on this date

    Calendar c= Calendar.getInstance();
    c.setTime(date);
    TimeZone tz = TimeZone.getTimeZone("Etc/GMT0");
    DateFormat df = DateFormat.getDateTimeInstance();
    df.setTimeZone(tz);
    System.out.println(df.format(new Date()));
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.DST_OFFSET, 0); 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!