Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a String to Date, almost done! [duplicate]

Tags:

java

date

paypal

Possible Duplicate:
Converting ISO8601-compliant String to java.util.Date

I'm trying to convert this String:

2011-06-07T14:08:59.697-07:00

To a Java Date, so far, here's what I did:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S");
Date date1 = sdf.parse("2011-06-07T14:08:59.697", new java.text.ParsePosition(0));

Almost everything is good, except the most important part, the timezone !! The problem with SimpleDateFormat is that it expect a TimeZone in +/-hhmm and mine is in +/-hh:mm format.

Also, and I don't know why, this works:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S Z");
Date date1 = sdf.parse("2011-06-07T14:08:59.697 -0700", new java.text.ParsePosition(0));

But this does not (the space before the timezone):

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SZ");
Date date1 = sdf.parse("2011-06-07T14:08:59.697-0700", new java.text.ParsePosition(0));

What is the correct format to transform this date 2011-06-07T14:08:59.697-07:00 to a java date ?

Thanks for your help!

like image 244
Cyril N. Avatar asked Dec 09 '25 09:12

Cyril N.


2 Answers

That looks like the ISO 8601 standard date and time format as it is used in XML. Unfortunately, Java's SimpleDateFormat doesn't support that format properly, because it can't deal with the colon in the timezone.

However, the javax.xml package contains classes that can deal with this format.

String text = "2011-06-07T14:08:59.697-07:00";
XMLGregorianCalendar cal = DatatypeFactory.newInstance().newXMLGregorianCalendar(text);

If you need it as a java.util.Calendar then you can call toGregorianCalendar() on it:

Calendar c2 = cal.toGregorianCalendar();

And ofcourse you can get a java.util.Date out of that:

Date date = c2.getTime();

You could also use the popular Joda Time library which natively supports this format (and has a much better API for dealing with dates and times than Java's standard library).

like image 150
Jesper Avatar answered Dec 11 '25 22:12

Jesper


Java SimpleDateFormat doesn't support colon in the timezone information. You should use other implementation such as JodaTime.

Example usage:

String dateString = "2011-06-07T14:08:59.697-07:00";
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern);
DateTime dateTime = dtf.parseDateTime(dateString);
System.out.println(dateTime);

maven pom.xml dependency if needed:

<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>1.6.2</version>
</dependency>

Hope it helps.

like image 42
lepike Avatar answered Dec 11 '25 23:12

lepike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!