Re: Date parsing problem
In article <yrjiql44xwo.fsf@despammed.com>,
Jukka Lahtinen <jtfjdehf@hotmail.com.invalid> wrote:
rossum <rossum48@coldmail.com> writes:
On 16 Apr 2009 13:28:40 +0300, Jukka Lahtinen
I need to parse date and time from a String containing
year-month-day hours:minutes:seconds and time zone.
The code in the SSCCE below works in java 1.3, but produces a
ParseException about unparseable date in java 1.5.
Why doesn't it work in 1.5 and how should I fix it?
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestSDF {
public static void main(String[] args) {
try {
String str = "2009-04-06 08:30:45+03";
String format = "yyyy-MM-dd HH:mm:sszz";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date date = sdf.parse(str);
System.out.println(date);
} catch (Exception e) {
System.out.print("Exception: ");
e.printStackTrace();
}
}
}
Read the 1.5 Javadoc for SimpleDateFormat, in particular the 'z' and
'Z' formats.
String str = "2009-04-06 08:30:45+0300";
String format = "yyyy-MM-dd HH:mm:ssZ";
Thanks, John and Rossum. I ended up appending two more zeroes before
calling sdf.
if (str.length() == 22) {
str = str + "00";
}
Looks like both z and Z work for the timezone symbol in SimpleDateFormat,
since Z for RFC 822 time zone also accepts general time zone for parsing.
Adding "00" will satisfy the parser, but it assumes that the offset is
zero minutes exactly. That assumption fails for many locales: Darwin &
Mumbai, for example. Only you can decide if the result is acceptable in
the context of your application:
<http://www.timeanddate.com/worldclock/>
--
John B. Matthews
trashgod at gmail dot com
<http://sites.google.com/site/drjohnbmatthews>