Reputation: 545
I'm a beginner in java programmeing.
I want to parse a complex date format : YYYY-MM-DDthh:mm:ssTZD
, for example 2014-09-24T21:32:39-04:00
I tried this :
String str_date="2014-09-24T21:32:39-04:00";
DateFormat formatter = new SimpleDateFormat("YYYY-MM-DDthh:mm:ss");
Date date = (Date)formatter.parse(str_date);
But for the timezone part (-04:00)
, i have no idea what to put (after the :ss)
Any help ?
Upvotes: 0
Views: 942
Reputation: 339837
Your string complies with the ISO 8601 standard. That standard is used as the default in parsing and generating strings by two excellent date-time libraries:
Merely pass your string to the constructor or factory method. A built-in formatter is automatically used to parse your string.
Unlike java.util.Date, in these two libraries a date-time object knows its own assigned time zone. The offset from UTC specified at the end of your string is used to calculate a number of milliseconds (or nanoseconds in java.time) since the Unix epoch of the beginning of 1970 in UTC time zone. After that calculation, the resulting date-time is assigned a time zone of your choice. In this example I arbitrarily assign a India time zone. For clarity this example creates a second date-time object in UTC.
DateTimeZone timeZoneIndia = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeIndia = new DateTime( "2014-09-24T21:32:39-04:00" , timeZoneIndia );
DateTime dateTimeUtc = dateTimeIndia.withZone( DateTimeZone.UTC );
Upvotes: 0
Reputation: 9648
Java7
SimpleDateFormat
documentation lists the timezone as z
, Z
, and X
and for you it looks like you want XXX
.
Java6
Java7 added X
specifier, but 6 still has the Z
and z
. However, you will have to modify the string first so that it either has no colon in the timezone or has GMT
before the -
:
String str_date="2014-09-24T21:32:39-04:00";
int index = str_date.lastIndexOf( '-' );
str_date = str_date.substring( 0, index ) + "GMT" + str_date.substring( index+1 );
Then you can use the format specifier z
Upvotes: 2
Reputation: 3682
If you are using Java < 7
then you'd need to remove ':'
from your input and parse it:
Here is an example:
public static void main(String[] args) throws ParseException {
String str_date="2014-09-24T21:32:39-04:00";
str_date = str_date.replaceAll(":(\\d\\d)$", "$1");
System.out.println("Input modified according to Java 6: "+str_date);
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date date = (Date)formatter.parse(str_date);
System.out.println(date);
}
prints:
Input modified according to Java 6: 2014-09-24T21:32:39-0400
Wed Sep 24 21:32:39 EDT 2014
Upvotes: 2