springboot 日期、数字格式化器


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

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值