Parsing custom time format with SimpleDateFormat

Posted by ggrigery on Stack Overflow See other posts from Stack Overflow or by ggrigery
Published on 2012-12-07T16:58:31Z Indexed on 2012/12/07 17:04 UTC
Read the original article Hit count: 245

Filed under:
|
|

I'm having trouble parsing a date format that I'm getting back from an API and that I have never seen (I believe is a custom format). An example of a date:

/Date(1353447000000+0000)/

When I first encountered this format it didn't take me long to see that it was the time in milliseconds with a time zone offset. I'm having trouble extracting this date using SimpleDateFormat though. Here was my first attempt:

String weirdDate = "/Date(1353447000000+0000)/";

SimpleDateFormat sdf = new SimpleDateFormat("'/Date('SSSSSSSSSSSSSZ')/'");

Date d1 = sdf.parse(weirdDate);
System.out.println(d1.toString());
System.out.println(d1.getTime());
System.out.println();

Date d2 = new Date(Long.parseLong("1353447000000"));
System.out.println(d2.toString());
System.out.println(d2.getTime());

And output:

Tue Jan 06 22:51:41 EST 1970
532301760

Tue Nov 20 16:30:00 EST 2012
1353447000000

The date (and number of milliseconds parsed) is not even close and I haven't been able to figure out why. After some troubleshooting, I discovered that the way I'm trying to use SDF is clearly flawed. Example:

String weirdDate = "1353447000000";

SimpleDateFormat sdf = new SimpleDateFormat("S");

Date d1 = sdf.parse(weirdDate);
System.out.println(d1.toString());
System.out.println(d1.getTime());

And output:

Wed Jan 07 03:51:41 EST 1970
550301760

I can't say I've ever tried to use SDF in this way to just parse a time in milliseconds because I would normally use Long.parseLong() and just pass it straight into new Date(long) (and in fact the solution I have in place right now is just a regular expression and parsing a long). I'm looking for a cleaner solution that I can easily extract this time in milliseconds with the timezone and quickly parse out into a date without the messy manual handling. Anyone have any ideas or that can spot the errors in my logic above? Help is much appreciated.

© Stack Overflow or respective owner

Related posts about java

Related posts about date