Henrique
Henrique

Reputation: 65

How to convert DateTime to Date?

In the Cotacoes class, I have the creation_date field, it is a Date, but on the server it is a DateTime. Upon receiving JSON, the following error occurs:

java.text.ParseException: Failed to parse date ["2018-11-05T12:12:37.307']: No time zone indicator

How to solve this problem? I use retrofit to make and receive calls from the server.

Cotacoes:

public class Cotacoes implements Serializable {

    private static final long serialVersionUID = 842387749350567455L;
    @SerializedName("quotation_id")
    @Expose
    private int quotation_id;
    //private int transaction_id;
    @SerializedName("pecas")
    @Expose
    private List<Pecas> pecas;
    @SerializedName("creation_date")
    @Expose
    private Date creation_date;
   // private int duration;
    @SerializedName("brand")
    @Expose
    private String brand;
    @SerializedName("vehicle")
    @Expose
    private String vehicle;

....
getters and setters
}

Retrofit:

public class APIRetrofit {
    public static final String BASE_URL = "http://server.net/";
    private static Retrofit retrofit = null;

    private static Gson gson = new GsonBuilder()
            .create();


    public static Retrofit getRetrofitClient() {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
        }
        return retrofit;
    }
}

Interface:

public interface APIService {

    interface ReturnFutureCallback<T> {
        void onSuccess(T retorno);

        void onFailure(T retorno);
    }

    @POST("/cotacao")
    @FormUrlEncoded
    Call<JsonQuotationResponse> listaCotacao(@Header("Authorization") String token, @Field("seller_company_id") String seller_company_id);

}

Upvotes: 1

Views: 318

Answers (2)

Cuong Nguyen
Cuong Nguyen

Reputation: 1018

  • I think, on sever, It's longtime or String, so creation_date field, it is a longtime or String

Upvotes: 1

EKN
EKN

Reputation: 1906

You have to create JsonDeserializer for parsing DateTime to a customized Date object.

For more details you can refer the following links:

https://kylewbanks.com/blog/String-Date-Parsing-with-GSON-UTC-Time-Zone

gson fails to parse using GsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")

Upvotes: 0

Related Questions