I am working on Xero accounts Apis In json response i am getting date like below
\"Date\": \"/Date(1455447600000+1300)/\",
also same date
I should like to contribute the modern solution
Pattern jsonDatePattern = Pattern.compile("/Date\\((\\d+)([+-]\\d{4})\\)/");
String dateFromJson = "/Date(1455447600000+1300)/";
Matcher m = jsonDatePattern.matcher(dateFromJson);
if (m.matches()) {
long epochMillis = Long.parseLong(m.group(1));
String offsetString = m.group(2);
OffsetDateTime dateTime = Instant.ofEpochMilli(epochMillis)
.atOffset(ZoneOffset.of(offsetString));
System.out.println(dateTime);
}
Output:
2016-02-15T00:00+13:00
This agrees with the date and time in your JSON date string and additionally informs you of the UTC offset.
I am using and warmly recommending java.time
, the modern Java date and time API. And discouraging the classes Date
, Calendar
and TimeZone
used in the question and in the other answer. They are long outdated, and the modern Java date and time API is so much nicer to work with.
Oracle tutorial: Date Time explaining how to use java.time
.
The +1300
is not a milliseconds offset, it's an hour + minute offset.
If you parse just the date part as a long:
Long longDate=Long.valueOf("1455447600000");
Date date = new Date(longDate);
System.out.println(date);
You get (I'm in GMT timezone)
Sun Feb 14 11:00:00 GMT 2016
And you can see that 11 + 13 = 24, and 24 hours is the next day.
You can get the timezone from the offset, knowing the offset is 13 hours and zero minutes:
Calendar c=Calendar.getInstance(TimeZone.getTimeZone(TimeZone.getAvailableIDs(13*3600*1000)[0]));
c.setTimeInMillis(longDate);
DateFormat df=DateFormat.getDateInstance();
df.setTimeZone(c.getTimeZone());
System.out.println(df.format(c.getTime()));
Which gives me
Feb 15, 2016
Here so I calculate the offset as being 13 hours, hence 13*3600 seconds, hence 13*3600*1000 milliseconds. So you can parse your string: what's before the plus sign is the time, what's after is the timezone.