我使用 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 日的唯一联系是它这是我最后一次在 PaaS 上重新启动 JAR
文件。我已通过 SSH
进入服务运行的环境并运行 date
。它返回 Tue Oct 24 17:54:23 UTC 2017
。你知道我做错了什么吗?
最佳答案
根据你所说的,我猜你的问题是 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)
}
);
}
关于java - LocalDate.now() 返回错误的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46917561/