如何验证Java中的时间格式是否符合预期

Mic*_*hal 0 java api validation rest timestamp

在我的带有@PathVariable("timestamp")的REST API控制器中,我必须验证时间戳格式是否符合ISO 8601标准:例如2016-12-02T18:25:43.511Z.

@RequestMapping("/v3/testMe/{timestamp}")
public class TestController {

    private static final String HARDCODED_TEST_VALUE = "{\n\t\"X\": \"01\",\n\t\"Y\": \"0.2\"\n}";

    @ApiOperation(nickname = "getTestMe", value = "Return TestMe value", httpMethod = "GET",
            authorizations = {@Authorization(value = OAUTH2,
                    scopes = {@AuthorizationScope(scope = DEFAULT_SCOPE, description = SCOPE_DESCRIPTION)})})
    @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String getTestMe(@PathVariable("timestamp") String timestamp) {

        if (timestamp != null)        {
            return HARDCODED_TEST_VALUE;
        }

        throw new ResourceNotFoundException("wrong timestamp format");
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要实现它的方式与上面的if-else语句类似,检查时间戳是否为null - 所以类似地我想添加类似的if-else来验证时间戳的格式并返回正文(如果是)或404错误代码,如果不是.

知道我可以用它做什么,请给我准备好的例子吗?我已经尝试使用正则表达式进行简单验证但不方便,但遗憾的是无论如何都没有...

She*_*hem 7

您可以使用Java 8 DateTimeFormatter并确保它解析字符串而不抛出异常.这是一个方法,true如果输入字符串是有效的ISO日期,则返回该方法:

boolean isValidIsoDateTime(String date) {
        try {
            DateTimeFormatter.ISO_DATE_TIME.parse(date);
            return true;
        } catch (DateTimeParseException e) {
            return false;
        }
    }
Run Code Online (Sandbox Code Playgroud)

要在响应正文中返回硬编码的测试值,您应该使用如下方法:

    public String getTestMe(@PathVariable("timestamp") String timestamp) {

            if (timestamp != null && isValidIsoDateTime(timestamp))        {
               return HARDCODED_TEST_VALUE;       
            }
            throw new ResourceNotFoundException("wrong timestamp format");


        }
Run Code Online (Sandbox Code Playgroud)