英文:
Converting String to Date using SimpleDateFormat returns incorrect format
问题
我有一个字符串s
,格式如下:05-10-2020
。
我想将这个字符串转换为以下格式的日期:dd-MM-yyyy
,这样我就可以在下面的查询中使用它,用于我的Sqlite数据库。
SimpleDateFormat simpledateformat = new SimpleDateFormat("dd-MM-yyyy");
String s = app.getDate(); // 返回"05-10-2020"
Date date = simpledateformat.parse(s);
String selectQuery = "SELECT * FROM User WHERE Date !=" + date;
但是date
返回的日期格式为:Mon Oct 05 00:00:00 GMT+03:00 2020
。
英文:
I have a String s
date in following format 05-10-2020
I want to convert this String to Date in following format dd-MM-yyyy
so I can use it in below query for my Sqlite db
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;
But date is returns date in follwoing format Mon Oct 05 00:00:00 GMT+03:00 2020
答案1
得分: 3
你应该使用带有 LocalDate
的 PreparedStatement
,如下所示:
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();
}
英文:
You should use PreparedStatement
with LocalDate
as this:
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();
}
答案2
得分: 0
你应该在关系型数据库操作中使用预处理语句。从你的第三行开始,尝试使用:
> PreparedStatement selectQuery = connectionObj.prepareStatement("SELECT * FROM User Where Date != ?");
> selectQuery.setDate(1, date);
> ResultSet res = selectQuery.executeQuery();
> res.next();
> // 根据需要操作结果集
英文:
You should use prepared statements for RDBMS work. From your third line on, try:
> PreparedStatement selectQuery = connectionObj.prepareStatement("SELECT * FROM User Where Date != ?");
> selectQuery.setDate(1, date);
> ResultSet res = selectQuery.executeQuery();
> res.next();
> // manipulate the resultset to your heart's content
答案3
得分: 0
它将提供一个简洁的解决方案。您可以根据您的代码动态进行调整。
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)));
您可以将其应用于项目中的相关位置。
英文:
It will provide a lean solution. You can dynamically adjust it to your code.
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)));
You can use it at the relevant place in your project.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论