【问题标题】:Converting String to Date using SimpleDateFormat returns incorrect format [duplicate]使用 SimpleDateFormat 将字符串转换为日期返回不正确的格式 [重复]
【发布时间】:2020-10-05 10:40:44
【问题描述】:

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

我想将此字符串转换为以下格式的日期dd-MM-yyyy 所以我可以在下面的查询中使用它来查询我的 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;

但 date 是以以下格式返回日期 Mon Oct 05 00:00:00 GMT+03:00 2020

【问题讨论】:

  • 您还期待什么?这是正确的日期。
  • 我在 db 中的日期是 DateTime 类型,我需要将它与相同的数据类型进行比较,这也是我正在尝试做的 DateTime。将字符串转换为日期对象,以便我可以比较两者。如果我错了,请纠正我
  • 你可以试试simpledateformat.format(s);,只是一个想法
  • @aryanagarwal format() 返回一个字符串
  • 顺便考虑扔掉长期过时且臭名昭著的麻烦SimpleDateFormat和朋友。看看您是否可以使用desugaring 或将ThreeTenABP 添加到您的Android 项目中,以便使用现代Java 日期和时间API 的java.time。使用起来感觉好多了。

标签: java android datetime jdbc simpledateformat


【解决方案1】:

您应该像这样使用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();
}

【讨论】:

  • 为什么我必须使用 PreparedStatement
  • @r_via 避免 SQL 注入和语法错误
  • @r_via - 检查SQL Injection。另外,这个答案教你另一个好东西try-with-resources
【解决方案2】:

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

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

selectQuery.setDate(1, date);

ResultSet res = selectQuery.executeQuery();

res.next();

// 随心所欲地操作结果集

【讨论】:

    【解决方案3】:

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

    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

    【讨论】:

    • 我的字符串采用以下格式“05-10-2020”,上面的代码也返回 04-10-2020 它应该是 05-10-2020
    猜你喜欢
    • 2018-11-03
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多