Skip to content

Commit

Permalink
Fix date converter
Browse files Browse the repository at this point in the history
  • Loading branch information
rtm516 committed Jul 24, 2024
1 parent d802714 commit 74fcad9
Showing 1 changed file with 33 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,34 +9,55 @@
import com.google.gson.JsonSerializer;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.TimeZone;

/**
* A Gson adapter for converting {@link Date} objects to and from the variation of ISO 8601 format used by Xbox Live.
* A Gson adapter for converting {@link Date} objects to and from the variations of ISO 8601 format used by Xbox Live.
*
* They can't decide on what format to use so we have to support all of them.
* 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'
*/
public class DateConverter implements JsonSerializer<Date>, JsonDeserializer<Date> {
private static final SimpleDateFormat dateFormat;
private static final DateTimeFormatter dateFormat;

static {
dateFormat = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ss.SSSSSSS");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS").withZone(ZoneOffset.UTC);
}

@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try {
return dateFormat.parse(json.getAsString());
} catch (ParseException e) {
String dateString = json.getAsString();

// Remove the Z from the end of the string
if (dateString.endsWith("Z")) {
dateString = dateString.substring(0, dateString.length() - 1);
}

// Add missing fractional digits
if (dateString.contains(".")) {
int fractionalDigits = dateString.length() - dateString.indexOf('.') - 1;
if (fractionalDigits < 7) {
dateString += "0".repeat(7 - fractionalDigits);
}
} else if (!dateString.isBlank()) {
dateString += ".0000000"; // Add fractional part if missing
}

Instant instant = dateFormat.parse(dateString, Instant::from);
return Date.from(instant);
} catch (Exception e) {
throw new JsonParseException(e);
}
}

@Override
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(dateFormat.format(src));
return new JsonPrimitive(dateFormat.format(src.toInstant()));
}
}
}

0 comments on commit 74fcad9

Please sign in to comment.