当前位置: 首页 > 知识库问答 >
问题:

提交Spring表单时的日期格式错误

微生恩
2023-03-14

我有一个使用Spring MVC和Thymeleaf的项目。我需要根据每个用户的偏好,用不同的格式显示日期。例如,用户A希望显示类似MM/dd/yyyy的日期,而用户B希望显示类似dd/MM/yyyy-y的日期。

为此,我使用以下thymeleaf参数:

th:value="${#dates.format(myDate, dateFormat)}"

值“dateFormat”基于用户首选项。这很好。

我的问题是日期输入在一个表单中,当我提交表单时,它没有采用好的格式。我总是得到MM/dd/yyyy。

如果我选择格式dd/MM/yyyy并输入18/01/2016,在我的spring controller中,我会获得“2017年6月1日00:00:00 CEST”,这对应于dd/MM/yyyy中的01/06/2017。

我该怎么做才能得到我想要的格式的日期?

这是我的代码:

<form th:action="@{/test}" th:object="${filter}" th:method="POST">
    <input type="date" th:type="date" class="form-control" th:id="myDate"
           th:name="myDate" th:value="${#dates.format(filter.myDate, dateFormat)}"/>
</form>

控制器:

@RequestMapping(value = "/test", method = RequestMethod.POST)
public String myTest(@ModelAttribute Filter filter, Model model) {

    Systeme.out.println(model.dateFormat);
    // dd/MM/yyyy

    Systeme.out.println(filter.myDate.toString());
    // Thu Jun 01 00:00:00 CEST 2017

    return "test";
}

共有3个答案

景哲
2023-03-14

我认为有问题,因为Spring不理解输入值是Date。变量myDate的类型是java.util.Date吗?

如果是,请尝试像这样注册格式化程序:

package your.pack.formatter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.format.Formatter;

public class DateFormatter implements Formatter<Date> { 

    final String defaultDateFormat = "dd.MM.yyyy";

    @Override
    public String print(Date object, Locale locale) {
        return new SimpleDateFormat(defaultDateFormat).format(object);
    }

    @Override
    public Date parse(String text, Locale locale) throws ParseException {
        return DateUtils.parseDate(text, defaultDateFormat);
    }
}

然后将其注册到您的配置中:

@Configuration
public class ConversionServiceConfig extends WebMvcConfigurerAdapter {

   @Bean
   public DateFormatter dateFormatter() {
       return new DateFormatter();
   }

   @Override
   public void addFormatters(FormatterRegistry registry) {
       registry.addFormatter(dateFormatter());
   }
}

但是我不知道如何让它按照你想要的那样动态工作…

用户首选项是存储在数据库中还是存储在属性中?

张瀚漠
2023-03-14

经过一天的研究,我发现Spring读取了Web请求中发送的值,并尝试将其与Filter对象绑定。

对于日期值,除了找到“MM/dd/yyyy”格式的值。如果你用另一种格式发送一个值,它不起作用。

要解决此问题,您可以使用注释“InitBinder”。

@InitBinder
private void dateBinder(WebDataBinder binder) {
    //The date format to parse or output your dates
    SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormat());
    //Create a new CustomDateEditor
    CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
    //Register it as custom editor for the Date type
    binder.registerCustomEditor(Date.class, editor);
}

将为每个 Web 请求执行此方法。在这里,我调用我的“dateFormat()”方法来获取用户首选项中的格式,并对Spring说它在Web请求中找到的所有java.util.Date都具有此格式。

这是我的完整代码

滤波器:

import java.util.Date;

@lombok.Data
public class TestDateFilter {
    private Date myDate;

    public TestDateFilter() {
        this.myDate = new Date();
    }
}

控制器:

@RequestMapping(value = "/testdate")
public String testDate(Model model) {
    model.addAttribute("filter", new TestDateFilter());
    return "testdate";
}

@RequestMapping(value = "/testdate", method = RequestMethod.POST)
public String testDatePost(@ModelAttribute("filter") TestDateFilter filter, Model model) {
    System.out.printf(filter.getLoadingStartDate().toString());
    System.out.printf(dateFormat());
    return "testdate";
}

@ModelAttribute("dateFormat")
public String dateFormat() {
    return userPreferenceService.getDateFormat();
}

@InitBinder
private void dateBinder(WebDataBinder binder) {
    //The date format to parse or output your dates
    SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormat());
    //Create a new CustomDateEditor
    CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
    //Register it as custom editor for the Date type
    binder.registerCustomEditor(Date.class, editor);
}

.HTML:

    <form th:action="@{/testdate}" th:object="${filter}" th:method="POST">
        <div class="row">
            <div class="col-xs-12 col-sm-6">
                <div class="input-group date">
                    <input type="date" th:type="date" class="form-control"
                           th:id="loadingStartDate" th:name="loadingStartDate"
                           th:value="${#dates.format(filter.loadingStartDate, dateFormat)}" />
                </div>
            </div>
        </div>
        <div class="row">
            <div class="form-group">
                <div class="col-xs-12 col-sm-12">
                    <button type="submit" class="btn btn-primary btn-lg pull-right">
                        submit
                    </button>
                </div>
            </div>
        </div>
    </form>
任云瀚
2023-03-14

您可以注释Date属性

    @DateTimeFormat(pattern = "dd/MM/yyyy")
    private Date dob;

自Spring 3.2 起没有 Joda 依赖性

 类似资料:
  • 我试图通过一个表单向数据库添加一个表。正在创建的实体称为相册,它有2个字段,艺术家和流派。这两者都是独立的实体。这两个字段用@ManyToOne进行了注释 当我提交表单时,这是我得到的错误: 以下代码是我的控制器的一部分: 下面的代码是百里香模板的一部分: 是什么导致了这个错误?

  • 我正在使用tinyMCE-4.0。16以cakePHP2的形式。4.当我单击submit时,表单不提交,并在控制台中出现以下错误 具有name='data[Research][description]'的无效窗体控件不可聚焦。 我在文本区使用HTML5验证“必需”。

  • 我正在尝试将DatePicker日期格式化为简单的数据格式(“yyyy-MM-dd HH: mm: ss Z”)。有人告诉我,我需要使用简单的数据格式将其解析为日期对象-简单的数据格式(“yyyy-MM-dd”),然后将其格式化为我需要的内容,如下所示。但是,我在尝试捕捉块中收到错误“重复局部变量eDate”。任何专家都可以查看我的代码并提出建议吗? 已更新

  • 我们使用带Spring垫和Jackson的SpringBoot。我们使用Java 8。 RestController。 控制器返回的RestObject。 当我用头发送GET请求时,它工作得很好。这就是答案。 但是: 时间戳字段为空。如何使其工作?

  • 问题内容: 我在解析我的代码中的平面文件后,试图转换作为文件存在于平面文件中的String 值。 我已经写了代码来做到这一点,但是当我格式化日期时,它总是给我一个指定日期超过1天的日期,有时它会加5:30。 以下是该代码: 上面的输出是 您能告诉我这里是什么问题吗?我在课堂上使用的模式有问题吗?还是代码有问题?我已经为此挠了很久。 问题答案: 您的系统时区不同。输出显示IST-或印度标准时间,与P

  • 下表显示可用于为图表中的日期时间字段创建用户定义的数据格式的说明符。 说明符 描述 D 将日显示为不带前导零的数字(1-31)。 DD 将日显示为带前导零的数字(01-31)。 M 将月份显示为不带前导零的数字(1-12)。 MM 将月份显示为带前导零的数字(01-12)。 MMM 将月份显示为缩写形式(Jan-Dec)。 MMMM 将月份显示为完整月份名(January-December)。 Y