2017-08-27 26 views
0

我試圖找出默認的java.time.LocalDateTime格式,當用戶在URL中傳遞日期作爲請求參數與QueryDSL一起使用時在傳遞到休息終點的時候爲LocalDateTime(jsr310)設置默認格式

我在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); 
    } 
} 

所以,默認值要短,但是預期這似乎不工作。

另外,如何重寫格式應用程序範圍內(不使用所述特定場@DateTimeFormat註解)

回答

0

該溶液不僅對於由QueryDSL使用的日期參數,但傳遞給彈簧的任何日期參數(還可以通過使用登記任何其他格式化器)

// 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 /本地時間/ LocalDateTime,它也可以被用於註冊爲約達日期時間格式化。

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