首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用OpenFeign格式化数据

用OpenFeign格式化数据
EN

Stack Overflow用户
提问于 2020-12-03 00:38:29
回答 1查看 500关注 0票数 1

我的冒牌客户定义如下:

代码语言:javascript
复制
@FeignClient(name = "${feign.name}",url = "${feign.url}",
        configuration = {DateFormatConfiguration.class})
public interface MyFeignClient {

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

}

其中:

代码语言:javascript
复制
 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);
            }
        });
    }
   }

然而,当我运行这个测试时:

代码语言:javascript
复制
@Test
public void test(){
    Date date= new GregorianCalendar(2000, 12, 31).getTime();
    myFeignClient.getResponse(date);
}

请求以这种格式发送:

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

->获取

我想要的是:

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

根据我的需要日期是格式化的。

我也尝试过这个解决方案,但两者都不起作用:

代码语言:javascript
复制
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;
        }
       }

有什么想法吗?

EN

回答 1

Stack Overflow用户

发布于 2020-12-03 14:48:34

您应该考虑尝试用以下内容替换所需的行:

代码语言:javascript
复制
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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65118245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档