spring-boot - 使用 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;
}
}
有任何想法吗 ?
解决方案
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);
推荐阅读
- ios - 表格视图单元格在编辑情绪中保持未选中状态
- python - 选择具有相同长度值的键,这是字典中计数最高的列表
- sql - ActiveRecord::StatementInvalid: PG::UndefinedColumn: 错误: 列“order_count”不存在时.have('order_count > 5')
- ios - 函数已创建,但从未调用,但仍在执行
- java - aws-ec2 java 网站托管在 amazon-ec2 上
- python - SQL在 SELECT 语句中使用通配符 <% 和占位符。(在带有 sqlite3 的 python 中)
- neo4j - Neo4j:按连接数组的最大值排序
- java - 如何为HashMap中的重复元素添加所有整数?
- css - 为什么我会收到意外的名称或十六进制数字错误?
- python - 矩形重叠