Why does 12:20 PM parse to 0:20 on the next day?
Posted
by Hanno Fietz
on Stack Overflow
See other posts from Stack Overflow
or by Hanno Fietz
Published on 2010-04-08T20:20:17Z
Indexed on
2010/04/08
20:23 UTC
Read the original article
Hit count: 376
I'm using java.text.SimpleDateFormat
to parse string representations of date/time values inside an XML document. I'm seeing all times that have an hour value of 12 shifted by 12 hours into the future, i. e. 20 minutes past noon gets parsed to mean 20 minutes past midnight the following day.
I wrote a unit test which seems to confirm that the error is made upon parsing (I checked the return values from getTime()
with the linux shell command date
). Now I'm wondering:
- is there a bug in the
parse()
method? - is there something wrong with the input string?
- am I using the wrong format string for the input?
The input data is taken from Yahoo's YWeather service. Here's the test and its output:
public class YWeatherReaderTest
{
public static final String[] rgDateSamples = {
"Thu, 08 Apr 2010 12:20 PM CEST",
"Thu, 08 Apr 2010 12:20 AM CEST"
};
public void dateParsing() throws ParseException
{
DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy K:m a z",
Locale.US);
for (String dtsSrc : YWeatherReaderTest.rgDateSamples) {
Date dt = formatter.parse(dtsSrc);
String dtsDst = formatter.format(dt);
System.out.println(dtsSrc);
System.out.println(dtsDst);
System.out.println();
}
}
}
Thu, 08 Apr 2010 12:20 PM CEST Fri, 09 Apr 2010 0:20 AM CEST Thu, 08 Apr 2010 12:20 AM CEST Thu, 08 Apr 2010 0:20 PM CEST
The second output line of the second iteration is slightly weird, because 00:20 isn't PM. The milliseconds value of the Date
object, however, corresponds to the (wrong) time of 20 minutes past noon.
© Stack Overflow or respective owner