【问题标题】:LocalDate.now() returns wrong dateLocalDate.now() 返回错误的日期
【发布时间】:2018-04-05 15:59:29
【问题描述】:

我使用 Spring Boot 编写了一个 REST 服务。 REST 服务在 PaaS 上运行。我有一个端点可以在数据库表中创建新项目。每次创建新项目时,我都会使用以下方法为其分配创建日期:

LocalDate currentDate = LocalDate.now();
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");

sql = "INSERT INTO my_table (" +
                "code, " +
                "description, " +
                "created_date)" +
                "VALUES (?, ?, ?)";

        jdbcTemplate.update(
                sql,
                new Object[]{
                        code,
                        description,
                        currentDate.format(df)
                }
        );

问题是 currentDate.format(df) 出现在 2017 年 10 月 17 日,而今天是 2017 年 10 月 24 日。我能看到的与 10 月 17 日的唯一联系是这是我最后一次重新启动 JAR PaaS 上的文件。我已经SSH 进入服务运行的环境并运行date。它返回Tue Oct 24 17:54:23 UTC 2017。任何想法我做错了什么?

【问题讨论】:

  • 为什么不在数据库中生成日期(并使用适当的日期列而不是 varchar)?

标签: java spring-boot localdate


【解决方案1】:

从你所说的我猜你的问题是 currentDate 在你的程序开始时被初始化然后你继续保存同一个日期,你可能有这样的事情

LocalDate currentDate = LocalDate.now();
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public void insert(String code, String description) {
  sql = "INSERT INTO my_table (" +
                "code, " +
                "description, " +
                "created_date)" +
                "VALUES (?, ?, ?)";

        jdbcTemplate.update(
                sql,
                new Object[]{
                        code,
                        description,
                        currentDate.format(df)
                }
        );
}

您应该在方法中移动日期的实例化

DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public void insert(String code, String description) {
  LocalDate currentDate = LocalDate.now();
  sql = "INSERT INTO my_table (" +
                "code, " +
                "description, " +
                "created_date)" +
                "VALUES (?, ?, ?)";

        jdbcTemplate.update(
                sql,
                new Object[]{
                        code,
                        description,
                        currentDate.format(df)
                }
        );
}

【讨论】:

  • 确实如此。谢谢!
  • 如果你对你有用,你能接受答案吗?谢谢
  • 确定只是等待“超时”过去。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-27
  • 2013-11-08
  • 2013-09-04
  • 2016-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多