Michal
Michal

Reputation: 573

How to validate that time format in Java is as expected

In my REST API Controller with @PathVariable("timestamp) I have to validate that timestamp format is complaint with ISO 8601 standard: eg. 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");
    }
}

The way of how I would like to achieve it is similiar to above if-else statement that check whether timestamp is null or not - so analogically I would like to add similiar if-else to validate format of timestamp and return body if so or 404 error code if it's not.

Any idea what I could use to do that and please give me ready example ? I've tried simple validation with regex but is not convenient and unfortunately didn't work anyway ...

Upvotes: 0

Views: 3651

Answers (2)

Makara Kann
Makara Kann

Reputation: 17

public class MyClass {
    public static void main(String args[]) {
        System.out.println("-------------OK--------------");
        String inputTimeString = "makara_kann";
        if (!inputTimeString.matches("^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$")){
             System.out.println("Invalid time string: " + inputTimeString);
        } else {
            System.out.println("valid time string: " + inputTimeString);
        }
    }
}

-------------OK-------------- Invalid time string: makara_kann

Upvotes: -1

Shem
Shem

Reputation: 565

You can use Java 8's DateTimeFormatter and make sure it parses the string without throwing an exception. Here's a method that that returns true if the input string is a valid ISO date:

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

To return the hardcoded test value in response body, you should use the method like this:

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

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


        }

Upvotes: 9

Related Questions