Reputation: 411
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.
Upvotes: 3
Views: 546
Reputation: 2034
Even though it's pretty much what you're doing now, I don't think there's much wrong with the manual method - other than it's a shame you have to go there!
I don't believe you can do it solely with SDF. This will give you a date reasonably 'elegantly':
Date date = new Date(Long.parseLong(weirdDate.split("[^\\d]")[6]));
I'm sure you've already considered it, but have you spoken to the producer of the API to see why they are outputting this value in such an odd format? If the interface is not public and/or not widespread they may consider changing it to something a bit more conventional.
Upvotes: 1
Reputation: 16392
Take the milliseconds value in the string:
/Date(1353447000000+0000)/
and pass that value as a long into the Date constructor:
Date date = new Date(1353447000000);
and format the date object using SimpleDateFormat.
Upvotes: 3