-2

I want to validate that calendar object should be as 2014-05-05T12:12:30.How to validate a this using regular expression

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Debesh Kuanr
  • 35
  • 1
  • 1
  • take a look at this thread, it is JS but very simil arhttp://stackoverflow.com/a/12756279/2362664 – Khinsu Jul 24 '14 at 15:35
  • Depending on what you really want to achieve you can use the built-in functionality of the Joda datetime library. Check out the function [ISODateTimeFormat.dateTimeParser()](http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTimeParser()). – MicSim Jul 24 '14 at 15:45

3 Answers3

3

The regex in Adam Yost's answer is close, but missing a closing bracket before the T... don't have enough rep to comment so here is the corrected version:

(19|20)[0-9][0-9]-(0[0-9]|1[0-2])-(0[1-9]|([12][0-9]|3[01]))T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]
Gus
  • 3,534
  • 1
  • 30
  • 39
sam
  • 71
  • 6
0

This regex will only match dates in that format with a few restrictions:

(19|20)[0-9][0-9]-(0[0-9]|1[0-2])-(0[1-9]|([12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]

This matches years 1900-2099, 12 months, up to 31 days, 24 hr clock, up to 59 minutes, up to 59 seconds

It should be noted that if you wish to validate whether or not something is a truly valid date (ie not Feb 30) you will need either a far more complex regex, or some simple code to wrap around it.

Adam Yost
  • 3,616
  • 23
  • 36
0

Regex is not the right tool for this requirement

You should use a date-time API for this requirement. Simply use LocalDateTime#parse to parse your date-time string and if it fails the validation, a DateTimeParseException will be thrown.

Note that java.time API is based on ISO 8601 and therefore you do not need a DateTimeFormatter to parse a date-time string which is already in ISO 8601 format (e.g. your date-time string, 2014-05-05T12:12:30).

Demo:

import java.time.LocalDateTime;
import java.time.format.DateTimeParseException;

class Main {
    public static void main(String args[]) {
        // Test date-time strings
        String[] arr = { "2014-05-05T12:12:30", "2014-05-05T123:12:30" };
        for (String strDateTime : arr) {
            System.out.print("Validating " + strDateTime);
            try {
                LocalDateTime.parse(strDateTime);
                System.out.println(" => It is a valid date-time string");
            } catch (DateTimeParseException e) {
                System.out.println(" => Validation failed, Error: " + e.getMessage());
                // throw e
            }
        }
    }
}

Output:

Validating 2014-05-05T12:12:30 => It is a valid date-time string
Validating 2014-05-05T123:12:30 => Validation failed, Error: Text '2014-05-05T123:12:30' could not be parsed at index 13

Learn more about the modern Date-Time API from Trail: Date Time.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110