Java Date Parsing Timezone causing parsing error
I am getting a ParseException with the following code and I cannot fix it:
String date = "Tue Mar 13 2012 10:48:05 GMT-0400";
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss zzzX"); //Tried zzzZ at the end as well
System.out.println(format.parse(date));
If I take out -0400 and the X (or Z) at the end of the SimpleDateFormat works fine, but once it's in the code, it just doesn't work. What character should I use instead? I am using Java 7.
Below is the parse error:
java.text.ParseException: Unparseable date: "Tue Mar 13 2012 10:48:05 GMT-0400"
at java.text.DateFormat.parse(DateFormat.java:357)
java.text.ParseException: Unparseable date: "Tue Mar 13 2012 10:48:05 GMT-0400"
at java.text.DateFormat.parse(DateFormat.java:357)
at com.throwaway.parse.DateParsing.testDate(TestDate:17)
source to share
Part of GMT
GMT-0400
your line is causing the problem.
The parameter Z
(or X
in java 7) only matches -4000
. You should exit GMT
using single quotes like this:
DateFormat format = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z", Locale.US);
Note that it is also recommended to set Local
in your DateFormat. Without that, your code won't work in other countries (like here in France ...).
source to share
Three problems with mixed use. Or:
- Use a single lowercase "z" and ":" separating your hour and time in your time zone when using "GMT (+/-) hh: mm" or
- Use one uppercase "Z" and drop "GMT" from your timezone and you can use the format "(+/-) hhmm" or
- Use one uppercase "X" and still leave "GMT", but you can use any hhmm zone format.
From the Javadoc:
- z Common time zone Pacific Standard Time; PST; GMT-08: 00
- Z RFC 822 timezone -0800
- X time zone ISO 8601 -08; -0800; -08: 00
source to share
If you always expect your timezone to be represented this way, you can put "GMT" in single quotes in the format string to prevent parsing:
EEE MMM dd yyyy HH:mm:ss 'GMT'XX
It's a bit strange that none of the built-in formats can parse it. Perhaps the Javadoc is incorrect when it lists GMT-08:00
as an example z
?
source to share