首页 > 解决方案 > 使用 OpenFeign 格式化日期

问题描述

我的 Feign 客户定义如下:

@FeignClient(name = "${feign.name}",url = "${feign.url}",
        configuration = {DateFormatConfiguration.class})
public interface MyFeignClient {

@GetMapping(value = "/test")
    ResponseEntity<MyResponse> getResponse(@RequestParam(value = "date") Date date);

}

在哪里 :

 class DateFormatConfiguration {
    
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

    @Bean
    public FeignFormatterRegistrar dateFeignFormatterRegistrar() {
        return formatterRegistry -> formatterRegistry.addFormatter(new Formatter<Date>() {
            @Override
            public Date parse(String text, Locale locale) throws ParseException {
                return df.parse(text);
            }
            @Override
            public String print(Date object, Locale locale) {
                return df.format(object);
            }
        });
    }
   }

但是,当我运行此测试时:

@Test
public void test(){
    Date date= new GregorianCalendar(2000, 12, 31).getTime();
    myFeignClient.getResponse(date);
}

请求以这种格式发送:

---> GET https:xxx/test?date=Wed%20Jan%2031%2000%3A00%3A00%20EST%202001

我想要的是:

---> GET https:xxx/test?date=2000-12-31

日期是我需要的格式化程序。

我也尝试过这个解决方案,但都没有工作:

class DateFormatConfiguration {
        
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    
        @Bean
        public JacksonEncoder feignEncoder() {
            return new JacksonEncoder(customObjectMapper());
        }
    
        @Bean
        public JacksonDecoder feignDecoder() {
            return new JacksonDecoder(customObjectMapper());
        }
    
        private ObjectMapper customObjectMapper(){
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setDateFormat(df);
            return objectMapper;
        }
       }

有任何想法吗 ?

标签: spring-bootjacksonobjectmapperopenfeign

解决方案


You should consider trying replace necessary lines with something like this:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");    
LocalDate date= LocalDate.ofInstant(new GregorianCalendar(2000, 12, 31).getTime().toInstant(), ZoneId.of(TimeZone.getDefault().getID()));
String dateFormatted = date.format(dtf);

推荐阅读