[英]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.在Cotacoes
类中,我有creation_date
字段,它是一个日期,但在服务器上它是一个日期时间。 Upon receiving JSON, the following error occurs:收到JSON后,出现如下错误:
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);
}
You have to create JsonDeserializer for parsing DateTime to a customized Date object.您必须创建 JsonDeserializer 以将 DateTime 解析为自定义的 Date 对象。
For more details you can refer the following links:有关更多详细信息,您可以参考以下链接:
https://kylewbanks.com/blog/String-Date-Parsing-with-GSON-UTC-Time-Zone 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") gson 无法使用 GsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") 解析
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.