Created
December 17, 2014 15:07
-
-
Save aegis123/0e5084280dfd29d22fdd to your computer and use it in GitHub Desktop.
A Gson Serializer/Deserializer for java.util.Date objects.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DateTypeDeserializer implements JsonDeserializer<Date>, JsonSerializer<Date> { | |
private static final String[] DATE_FORMATS = new String[]{ | |
"yyyy-MM-dd'T'HH:mm:ssZ", | |
"yyyy-MM-dd'T'HH:mm:ss", | |
"yyyy-MM-dd", | |
"EEE MMM dd HH:mm:ss z yyyy", | |
"HH:mm:ss", | |
"MM/dd/yyyy HH:mm:ss aaa", | |
"yyyy-MM-dd'T'HH:mm:ss.SSSSSS", | |
"yyyy-MM-dd'T'HH:mm:ss.SSSSSSS", | |
"yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'", | |
"MMM d',' yyyy H:mm:ss a" | |
}; | |
@Override | |
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { | |
if (json.isJsonPrimitive()) { | |
return new Date(json.getAsLong()); | |
} | |
for (String format : DATE_FORMATS) { | |
try { | |
return new SimpleDateFormat(format, Locale.US).parse(json.getAsString()); | |
} catch (ParseException ignored) { | |
} | |
} | |
throw new JsonParseException("Unparseable date: \"" + json.getAsString() | |
+ "\". Supported formats: \n" + Arrays.toString(DATE_FORMATS)); | |
} | |
@Override | |
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { | |
if (false) { | |
return new JsonPrimitive(new SimpleDateFormat(DATE_FORMATS[0], Locale.US).format(src)); | |
} else { | |
return new JsonPrimitive(src.getTime()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html#iso8601timezone