0

java.time.LocalDateTime当用户在与 QueryDSL 结合使用时将 URL 中的日期作为请求参数传递时,我试图找出默认格式

我查看了QuerydslPredicateArgumentResolver, 并以DateTimeFormatterRegistrar并找到了默认读取方式结尾:

private DateTimeFormatter getFormatter(Type type) {
    DateTimeFormatter formatter = this.formatters.get(type);
    if (formatter != null) {
        return formatter;
    }
    DateTimeFormatter fallbackFormatter = getFallbackFormatter(type);
    return this.factories.get(type).createDateTimeFormatter(fallbackFormatter);
}

private DateTimeFormatter getFallbackFormatter(Type type) {
    switch (type) {
        case DATE: return DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
        case TIME: return DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
        default: return DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
    }
}

因此,默认值应该是 SHORT,但是它似乎没有按预期工作。

此外,如何覆盖应用程序范围内的格式(不使用特定于字段的@DateTimeFormat注释)

4

2 回答 2

4

你可以使用这个代码

@Configuration
public class DateTimeFormatConfiguration implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
        registrar.setUseIsoFormat(true);
        registrar.registerFormatters(registry);
    }
}

https://github.com/jhipster/jhipster-sample-app-hazelcast/blob/master/src/main/java/io/github/jhipster/sample/config/DateTimeFormatConfiguration.java

于 2018-07-05T16:08:34.600 回答
0

此解决方案不仅适用于 QueryDSL 使用的日期参数,还适用于传递给 spring 的任何日期参数(也可用于注册任何其他格式化程序)

// This example uses ISO format for both java.util.Date classes and jsr310 classes, you can change the format to whatever suitable for your case
@Configuration
public static class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        super.addFormatters(registry);

        DateFormatter javaUtilDateFormatter = new DateFormatter();
        javaUtilDateFormatter.setIso(ISO.DATE_TIME);

        DateTimeFormatter jsr310Formatter = DateTimeFormatter.ISO_DATE_TIME;

        DateFormatterRegistrar javaUtilDate = new DateFormatterRegistrar();
        javaUtilDate.setFormatter(javaUtilDateFormatter);
        javaUtilDate.registerFormatters(registry);

        DateTimeFormatterRegistrar jsr310 = new DateTimeFormatterRegistrar();
        jsr310.setDateTimeFormatter(jsr310Formatter);
        jsr310.setDateFormatter(jsr310Formatter);
        jsr310.setTimeFormatter(jsr310Formatter);
        jsr310.registerFormatters(registry);

    }
}

上面的类为 java.util.date 和 jsr310 LocalDate/LocalTime/LocalDateTime 注册了格式化程序,它也可以用于注册 joda datetime 的格式化程序。

完整代码示例:https ://github.com/project-seeds/spring-argument-resolver-parser

于 2017-08-27T13:14:18.370 回答