springboot 日期、数字格式化器
应用:将指定格式的日期、数字字符串转换为日期、数字
******************
相关注解
@DateTimeFormat:将指定格式的字符串转换为日期
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
public @interface DateTimeFormat {
String style() default "SS";
ISO iso() default ISO.NONE;
String pattern() default "";
enum ISO {
DATE, TIME, DATE_TIME, NONE
}
}
@NumberFormat:将指定格式的字符串转换为数字
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
public @interface NumberFormat {
Style style() default Style.DEFAULT;
String pattern() default "";
enum Style {
DEFAULT, NUMBER, PERCENT, CURRENCY
}
}
******************
示例
**************
pojo 层
Order
@Data
public class Order {
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime orderTime;
@NumberFormat(pattern = "¥ ##,###.00")
private BigDecimal amount;
}
**************
controller 层
HelloController
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(Order order){
System.out.println("orderTime:"+order.getOrderTime());
System.out.println("amount:"+order.getAmount());
return "success";
}
@RequestMapping("/hello2")
public String hello2(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime orderTime,
@NumberFormat(pattern = "¥ ##,###.00") BigDecimal amount){
System.out.println("orderTime:"+orderTime);
System.out.println("amount:"+amount);
return "success";
}
}
******************
使用测试
localhost:8080/hello?orderTime=2020-07-12 01:01:01&amount=¥ 232.121
2020-07-12 09:48:13.688 INFO 2456 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-07-12 09:48:13.697 INFO 2456 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 8 ms
orderTime:2020-07-12T01:01:01
amount:232.121
localhost:8080/hello2?orderTime=2020-06-12 09:12:34&amount=¥ 232.132
orderTime:2020-06-12T09:12:34
amount:232.132