简体   繁体   中英

unexpected results with GMT parsing in java

I am using the code below to parse a String into a date GMT->EDT. I don't understand the results I am seeing.

        SimpleDateFormat dformat = new SimpleDateFormat("yyyyMMdd-hh:mm:ss");
        TimeZone gmt = TimeZone.getTimeZone("GMT");
        dformat.setTimeZone(gmt);
        Date d = dformat.parse(time);

If time = "20111019-13:00:00", then d ends up being Wed Oct 19 09:00:00 EDT 2011. However, if time = "20111019-12:59:59", d somehow ends up being Tue Oct 18 20:59:59 EDT 2011. How can this be?

You meant HH:mm:ss for the time component, not hh:mm:ss . It was using the 12-hour clock, and interpreting 12:59:59 as effectively 00:59:59.

Note that your parsing does not perform a conversion to a particular time zone - because Date doesn't know about time zones . You're only seeing EDT because (I suspect) you're printing out d.toString() , which always uses the local time zone.

The Java date/time API is pretty awful - if you possibly can, I'd strongly advise you to move to Joda Time instead, where you would use a DateTime which does have a time zone... and lets you convert between them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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