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)注解。

发布了67 篇原创文章 · 获赞 1 · 访问量 1840

猜你喜欢

转载自blog.csdn.net/qq_15060345/article/details/100533949