I've been reading some questions like Java Gson to Json Conversion or Gson to json conversion with two DateFormat but I'm stilling without find a solution. The problems is that when I create a new user, I'm using SimpleDateFormat to set their register date:
long date = Calendar.getInstance(new Locale("es","ES")).getTimeInMillis();
DateFormat formatter = new SimpleDateFormat(FORMATO_FECHA, new Locale("es", ""));
return formatter.format(date);
This date is storing in mysql as "2022-10-12 13:54".
Then, when I recovery the user's data (for example when login), I use Gson
JSONObject jsUser = aDatas.getJSONObject("result");
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(java.util.Date.class, new DateDeserializer());
Gson gson = gsonBuilder.create();
User user = gson.fromJson(String.valueOf(jsUser),User.class);
My user java model has a field to store the registration date as a Date:
class User{
...
private Date mRegistrationDate;
...
}
The DateDeserializer class:
public class DateDeserializer implements JsonDeserializer<java.util.Date> {
private static final String[] DATE_FORMATS = new String[] {
"MMM dd, yyyy HH:mm:ss",
"MMM dd, yyyy",
"yyyy-MM-dd HH:mm:ss"
};
@Override
public Date deserialize(JsonElement jsonElement, Type typeOF,
JsonDeserializationContext context) throws JsonParseException {
for (String format : DATE_FORMATS) {
try {
return new SimpleDateFormat(format, Locale.US).parse(jsonElement.getAsString());
} catch (ParseException e) {
}
}
throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString()
+ "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
}
}
If I want to show the user registration date, it's shown as "Wed Oct 12 15:45:13 GMT+00:00 2022". That break's showing the following:
java.text.ParseException: Unparseable date: "Wed Oct 12 15:45:13 GMT+00:00 2022" (at offset 0)
I tried using old gson version but it does not work.
I'm using Volley to post and retrieve json data from an api.
I hope find a solution soon. Thanks in advance.