Parsing a Date in Java with a weird TimeZone
I'm getting dates sent to my application in the following format:
yyyy-MM-dd'T'HH:mm:ss.SSS-04:00
The problem is the TimeZone, it doesn't follow the Z format (-0400) and it doesn't follow the z format (GMT-04:00).
Is there another format option I'm missing or can I input a way to parse t开发者_Go百科hese TimeZones?
Consider switching to Joda time - it offers a lot more flexibility and readability than the java native date libraries, including handling that time zone style (that's one of the key reasons I switched).
The naive approach is quick to develop and simple.
class TimeTest {
public static void main(String[] args) {
String s = "yyyy-MM-dd'T'HH:mm:ss.SSS-04:00";
String t = "yyyy-MM-dd'T'HH:mm:ss.SSS-0400";
System.out.println(s + " --> " + fix(s));
System.out.println(t + " --> " + fix(t));
}
static String fix(String s) {
int last = s.lastIndexOf(":");
if(last == s.length() - 3) {
s = s.substring(0,last) + s.substring(last+1);
}
return s;
}
}
You appear to be getting an XSD dateTime format. If you want to stick with pure out of the box Java look at javax.xml.datatype.XMLGregorianCalendar which was built to handle that sort of thing.
However as another poster has said you'd probably have an easier time using a third party library such as Joda time. Java Calendar objects are always a bit cumbersome to use.
精彩评论