使用SimpleDateFormat将字符串转换为日期返回错误的格式

问题描述

我有一个字符串s日期,格式为05-10-2020

我想将此字符串转换为以下格式的dd-MM-yyyy 所以我可以在下面的查询中为我的Sqlite数据库使用它

SimpleDateFormat simpledateformat = new SimpleDateFormat("dd-MM-yyyy");
String s = app.getDate(); // returns "05-10-2020"
Date date = simpledateformat.parse(s);
String selectQuery = "SELECT * FROM User Where Date !=" + date;

但是日期是返回日期,格式为Mon Oct 05 00:00:00 GMT+03:00 2020

解决方法

您应该将PreparedStatementLocalDate一起使用,

LocalDate ld = LocalDate.parse(app.getDate(),DateTimeFormatter.ofPattern("dd-MM-uuuu"));
String selectQuery = "SELECT * FROM User Where Date != ?";
try (PreparedStatement ps = con.prepareStatement(selectQuery)) {
    ps.setObject (1,ld);
    // ...
} catch (SQLException e) {
    e.printStackTrace();
}
,

对于RDBMS工作,应使用准备好的语句。从第三行开始,尝试:

PreparedStatement selectQuery = connectionObj.prepareStatement(“ SELECT * FROM User Where Date!=?”);

selectQuery.setDate(1,date);

ResultSet res = selectQuery.executeQuery();

res.next();

//根据您的内心需求操纵结果集

,

它将提供精益解决方案。您可以根据您的代码动态调整它。

String dateStr = "Mon Oct 05 00:00:00 GMT+03:00 2020";
 
DateFormat formatOne= new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
DateFormat formatSecond= new SimpleDateFormat("dd-MM-yyyy");
System.out.println(formatSecond.format(formatOne.parse(dateStr)));

您可以在项目中的相关位置使用它。

DEMO

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...