简体   繁体   中英

How can I parse a Date String with the format “\/Date(1339638938087-0500)\/” in Java?

I have String with the format "\\/Date(1339638938087-0500)\\/" from a web service api.

Using java, how can I put this into a org.joda.time.DateTime variable?

You need to extract these two bits of information:

  • -2208967200000: milliseconds since the unix epoch (January 1st 1970 UTC)
  • -0600: offset from UTC

This assumes that the example represents January 1st 1900 at midnight local time - as the -2208967200000 part represents 6am UTC.

To convert this into a Joda Time DateTime , you should extract the two parts (get rid of everything outside the brackets, and then either use the length to split it, or find the middle +/- symbol).

Next, parse the first part as a long for the millis section. Then, parse the second part - probably as hours, minutes and sign separately. (I'm assuming it's always in the form xHHmm where x is the sign, HH is the minutes as two digits, and mm is the hours as two digits.)

Create a fixed time zone for the offset using DateTimeZone.forHoursMinutesOffset or something similar.

Finally, create the time with

new DateTime(millis, zone);

Oh, and then kick whoever's producing such a horrible format...

this look like unix timestamp

The unix time stamp is a way to track time as a running total of seconds. This count starts at the Unix Epoch on January 1st, 1970

If the "2208967200000" is a time in milliseconds since January 1, 1970, 00:00:00, you can use it in constructor for Date(time);

String dateStr="Date(-2208967200000-0600)";
String timeInMillis=dateStr.Split("-")[1];
String utcStr=dateStr.Split("-")[2].Substring(0,4);
Date d=new Date(Long.parseLong(timeInMillis));

if you want you can handle utcStr if it is necessary (if the second part after "-" is a time zone)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM