Java Date to UTC using gson

后端 未结 4 471
死守一世寂寞
死守一世寂寞 2020-12-05 00:04

I can\'t seem to get gson to convert a Date to UTC time in java.... Here is my code...

Gson gson = new GsonBuilder().setDateFormat(\"yyyy-MM-dd\'T\'HH:mm:ss.         


        
4条回答
  •  清歌不尽
    2020-12-05 00:38

    The solution that worked for me for this issue was to create a custom Date adapter (P.S be carefull so that you import java.util.Date not java.sql.Date!)

    public class ColonCompatibileDateTypeAdapter implements JsonSerializer, JsonDeserializer< Date> {
    private final DateFormat dateFormat;
    
    public ColonCompatibileDateTypeAdapter() {
      dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") {
            @Override
            public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos) {
                StringBuffer rfcFormat = super.format(date, toAppendTo, pos);
                return rfcFormat.insert(rfcFormat.length() - 2, ":");
            }
    
            @Override
            public Date parse(String text, ParsePosition pos) {
                if (text.length() > 3) {
                    text = text.substring(0, text.length() - 3) + text.substring(text.length() - 2);
                }
                return super.parse(text, pos);
            }
        };
    
    
    }
    
    @Override public synchronized JsonElement serialize(Date date, Type type,
        JsonSerializationContext jsonSerializationContext) {
      return new JsonPrimitive(dateFormat.format(date));
    }
    
    @Override public synchronized Date deserialize(JsonElement jsonElement, Type type,
        JsonDeserializationContext jsonDeserializationContext) {
      try {
          return dateFormat.parse(jsonElement.getAsString());
      } catch (ParseException e) {
        throw new JsonParseException(e);
      }
    }}
    

    and then use it while creating GSON object

    Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new ColonCompatibileDateTypeAdapter()).create();
    

提交回复
热议问题