0

I am getting datetime in UTC as json string from webservice. I'm using own date deserializer to convert string in local datetime as follow:

public class DateDeserializer implements JsonDeserializer<Date> {

    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Date deserialize(JsonElement element, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {

        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

        try {
            return sdf.parse(element.getAsString());
        } catch (ParseException e) {
            return null;
        }
    }
}

I need to display the datetime in local datetime (specified by system timezone) with custom date format. So I created gson object and used setDateFormat() as given in the fragment code.

public class OrdersList extends Fragment {
    private OrdersAdapter adapter;
    private List<OrdersData> ordersData = new ArrayList<>();
    private Type ctp = new TypeToken<Collection<OrdersData>>() {}.getType();

    Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy KK:mm a").registerTypeAdapter(Date.class, new DateDeserializer()).create();
    //...
}

My issue is I'm getting time in TextView as Tue May 10 17:20:07 IST 2016 where as I expect it to be May 10, 2016 05:20 pm

Datetime given by webservice 2016-05-10 11:50:07

Rajan Sharma
  • 103
  • 1
  • 12
  • `setDateFormat` is useless since you're using your own `TypeAdapter`. Not that `SimpleDateFormat` is not thread safe. Careful while using it in a multithreaded environment. Finally, a `Date` doesn't have a format. Its `toString` implementation simply prints out a default format. If you want something different, you'll need to format it yourself when you're about to display it. – Sotirios Delimanolis Jul 22 '16 at 15:15
  • Actually I am not from java background so first trying to understand "thread safe" and alternative. Meanwhile I have a question. Do I need to format date each time for each position as I'm using an adapter. Is there no way in gson to get only requested datetime format (I understand that would be string) at once? – Rajan Sharma Jul 22 '16 at 18:28

0 Answers0