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.
I adapted the marked solution and parametrized the DateFormat:
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
public class GsonDateFormatAdapter implements JsonSerializer, JsonDeserializer {
private final DateFormat dateFormat;
public GsonDateFormatAdapter(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
@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);
}
}
}