Android:无法从String值构造java.sql.Timestamp的实例

我开发了一个REST API,我正在尝试使用Android连接到它。 以下是我的代码。

private void restCall() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(URL) .addConverterFactory(GsonConverterFactory.create()) .build(); YourEndpoints request = retrofit.create(YourEndpoints.class); SetupBean setupBean = new SetupBean(); setupBean.setIdPatient(1); setupBean.setCircleType(1); setupBean.setFamiliarity(1); setupBean.setValence(2); setupBean.setArousal(3); setupBean.setDateCreated(Common.getSQLCurrentTimeStamp()); setupBean.setLastUpdated(Common.getSQLCurrentTimeStamp()); Call yourResult = request.insertSetup(setupBean); yourResult.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { try { Log.d("MainActivity", "RESPONSE: " + response.errorBody().string()); } catch(Exception e) { e.printStackTrace(); } } @Override public void onFailure(Call call, Throwable t) { try { t.printStackTrace(); Log.d("MainActivity", "RESPONSE: "+"FAILED"); } catch(Exception e) { e.printStackTrace(); } } }); } 

当我运行它时,它显示以下错误

 Can not construct instance of java.sql.Timestamp from String value 'Jun 9, 2016 4:24:37 PM': not a valid representation (error: Failed to parse Date value 'Jun 9, 2016 4:24:37 PM': Can not parse date "Jun 9, 2016 4:24:37 PM": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd")) 

因此,转换Timestamp似乎存在问题。 在我的Bean类中,下面是定义Timestamp方式。

 public void setDateCreated(Timestamp dateCreated) { this.dateCreated = dateCreated; } public Timestamp getLastUpdated() { return lastUpdated; } 

在我的restCall()方法中,我调用Common.getSQLCurrentTimeStamp()来生成时间戳。 以下是该方法。

 public static Timestamp getSQLCurrentTimeStamp() { java.util.Date date = new java.util.Date(); Timestamp t = new Timestamp(date.getTime()); System.out.println(t); return t; } 

所以,当我运行restCall()方法时,为什么我得到这个Can not construct instance of java.sql.Timestamp from String value 'Jun 9, 2016 4:24:37 PM': not a valid representation (error: Failed to parse Date value 'Jun 9, 2016 4:24:37 PM': Can not parse date "Jun 9, 2016 4:24:37 PM": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))错误? 我该如何解决?

我自己解决了这个问题。 Retrofit 2正在使用GSON,因此您必须手动提供日期时间转换器

 Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss") .create(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(URL) .addConverterFactory(GsonConverterFactory.create(gson)) .build();