spring mvc 时间日期转换(@DateTimeFormat 注解)

两种用法示例:

    @GetMapping("/date")
	public String datest(@DateTimeFormat(iso=ISO.DATE) Date date){
		System.out.println(date);
		return "lalalal";
	}
    @GetMapping("/date")
	public String datest(@DateTimeFormat(pattern = "yyyy/MM/dd") Date date){
		System.out.println(date);
		return "lalalal";
	}

使用 @DateTimeFormat 注解有两种做法,如上面代码所示。

示例说明:

第一种是按照ISO国际标准的日期时间格式解析参数中的日期时间的,具体格式为此枚举变量:

	/**
	 * Common ISO date time format patterns.
	 */
	enum ISO {

		/**
		 * The most common ISO Date Format {@code yyyy-MM-dd},
		 * e.g. "2000-10-31".
		 */
		DATE,

		/**
		 * The most common ISO Time Format {@code HH:mm:ss.SSSZ},
		 * e.g. "01:30:00.000-05:00".
		 */
		TIME,

		/**
		 * The most common ISO DateTime Format {@code yyyy-MM-dd'T'HH:mm:ss.SSSZ},
		 * e.g. "2000-10-31T01:30:00.000-05:00".
		 * <p>This is the default if no annotation value is specified.
		 */
		DATE_TIME,

		/**
		 * Indicates that no ISO-based format pattern should be applied.
		 */
		NONE
	}

第二种是按照自定义的模式来解析时间,模式字符串的定义与遵循以下规则(摘自jdk 1.8 SimpleDateFormat):

  • The following pattern letters are defined (all other characters from 'A' to 'Z' and from 'a' to 'z' are reserved):
  • The following examples show how date and time patterns are interpreted in the U.S. locale. The given date and time are 2001-07-04 12:08:56 local time in the U.S. Pacific Time time zone.

其他补充:

@ExceptionHandler 异常处理:

	@ExceptionHandler(Exception.class)
	public String handle(Exception exception){
		if (exception instanceof MethodArgumentTypeMismatchException) {
			return "传入参数格式不正确或参数解析异常!";
		}
		return exception.getMessage();
	}

如上所示,利用此注解@ExceptionHandler就可以实现对异常的处理。

若此示例代码段放在@Controller类中,就只可以处理它所在类被请求过程中发生的异常。如果需要处理多个@Controller类被请求过程中发生的异常,就需要将此代码段放在单独的一个类中,并且这个类需要加上@ControllerAdvice(或@RestControllerAdvice)注解。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值