spring - SimpleDateFormat 将日期字符串解析为错误值
问题描述
我有一个到达控制器的日期输入,它执行从字符串到日期的转换。
问题是,映射方法总是比我预期的少一天返回。如果我通过30/12/2010
它,它会返回一个 Date 对象,29/12/2010
并将其作为它的值。
我已经用一个在 Mapper 之后添加一天的小方法解决了它,但我不知道这是否是最正确的方法:
public class DateMapperImpl implements DateMapper {
@Override
public String dateToString(Date date, String format) {
return date != null ? new SimpleDateFormat(format).format(date) : null;
}
@Override
public Date stringToDate(String date, String format) {
try {
return date != null ? addDayDate(new SimpleDateFormat(format).parse(date)) : null;
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
public Date addDayDate(Date fecha) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(fecha);
calendar.add(Calendar.DAY_OF_YEAR, 1);
return calendar.getTime();
}
}
你知道如何正确解决它吗?
解决方案
我已经找到了解决方案。就我而言,有必要在 Application 类中添加此方法。
@SpringBootApplication
public class BooksApplication {
public static void main(String[] args) {
SpringApplication.run(BooksApplication.class, args);
}
@PostConstruct
public void init(){
// Setting Spring Boot SetTimeZone
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}
}
非常感谢您的回答,因为他们引导我以不同的心态寻找信息。
解决方案
推荐阅读
- javascript - JavaScript 中有字节大小的数据类型吗?
- amazon-web-services - 如何使用 cognito 验证我的 api 网关?
- html - 为在线视频课程创建产品页面的最简单的分步方法是什么?
- javascript - ijavascript / Jupyter Notebook JavaScript - 如何在没有错误的情况下重新运行单元格(就像使用 Python 一样)
- sas - 如何在 SAS 中处理字符串
- reactjs - 我们可以通过在响应对象中登录Google Auth来获取(职位名称)吗
- sql - 如何在 SQL Server 中包含字符串时应用百分比过滤器
- r - 用于循环具有唯一值的字符串的 R 函数
- amazon-elastic-beanstalk - 如何在 AWS EB 中以 git-commit-id 命名已部署的应用程序版本?
- flutter - 如何使用 Riverpod 创建开发中的通用组件?