首页 > 解决方案 > 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"));
    }

}

非常感谢您的回答,因为他们引导我以不同的心态寻找信息。

标签: springspring-bootsimpledateformat

解决方案


推荐阅读