Skip to content

Instantly share code, notes, and snippets.

@philo-ng
Last active December 27, 2016 23:25
Show Gist options
  • Select an option

  • Save philo-ng/f7e312853bccd26b4f4ca77e65355353 to your computer and use it in GitHub Desktop.

Select an option

Save philo-ng/f7e312853bccd26b4f4ca77e65355353 to your computer and use it in GitHub Desktop.
Deserialize old Microsoft Json date
private static class MicrosoftJsonDate {
private static final int DATE_GMT0_GROUP = 1;
private static final int OFFSET_GROUP = 2;
private static Pattern json_date_pattern
= Pattern.compile("^\\/Date\\(([-]?\\d+)([-\\+]([01]\\d|2[0-3])[0-5]\\d)?\\)\\/$");
private static HashMap<String, Integer> offsetInMillisMap
= new HashMap<>();
public static Date deserialize(String json_date) throws IllegalStateException {
Matcher m = json_date_pattern.matcher(json_date);
if(m.find()) {
Long date = Long.parseLong(m.group(DATE_GMT0_GROUP)) + getOffsetInMillis(m.group(OFFSET_GROUP));
return new Date(date);
}
else {
throw new IllegalStateException("The value '" + json_date + "' is an invalid Microsoft JSON date.");
}
}
private static Integer getOffsetInMillis(String offset) {
if (offset == null || offset.length() == 0) {
return 0;
}
else if (offsetInMillisMap.containsKey(offset)) {
return offsetInMillisMap.get(offset);
}
else {
Integer offsetInMillis = TimeZone
.getTimeZone("GMT" + offset)
.getRawOffset();
offsetInMillisMap.put(offset, offsetInMillis);
return offsetInMillis;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment