1

I am looking for a Java regex pattern for yyyymmddhhmmss format. It should also check for the leap years.

Below is the pattern which checks only yyyymmdd and leap year but now I need to extend it to yyyymmddhhmmss (so that it includes 24-hour time format validation).

 public static boolean isValidFormat(String format) {
    String pattern = "(?:(?:(?:(?:(?:[13579][26]|[2468][048])00)|(?:[0-9]{2}(?:(?:[13579][26])|(?:[2468][048]|0[48]))))(?:(?:(?:09|04|06|11)(?:0[1-9]|1[0-9]|2[0-9]|30))|(?:(?:01|03|05|07|08|10|12)(?:0[1-9]|1[0-9]|2[0-9]|3[01]))|(?:02(?:0[1-9]|1[0-9]|2[0-9]))))|(?:[0-9]{4}(?:(?:(?:09|04|06|11)(?:0[1-9]|1[0-9]|2[0-9]|30))|(?:(?:01|03|05|07|08|10|12)(?:0[1-9]|1[0-9]|2[0-9]|3[01]))|(?:02(?:[01][0-9]|2[0-8])))))$";
    boolean matches = Pattern.matches(pattern, format);  
    return matches;
 }

Thanks.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
user3492471
  • 93
  • 2
  • 16

4 Answers4

4

Here is a non-regex way to validate datetime values.

import java.text.*;
...
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
sdf.setLenient(false);
try {
       Date dt2 = sdf.parse("20150229105950");
       System.out.println(dt2);
}
catch (Exception exc) {
    System.out.println("NOT VALID");
}

See the IDEONE demo

In order to also validate 24-hour time with your regex, you need to append this to it:

(?:0[0-9]|1[0-9]|2[0-3])(?:[0-5][0-9]){2}

The (?:0[0-9]|1[0-9]|2[0-3]) part will validate numbers from 00 to 23 and (?:[0-5][0-9]){2} will validate minutes and seconds.

Then, your regex will look like:

(?:(?:(?:(?:(?:[13579][26]|[2468][048])00)|(?:[0-9]{2}(?:(?:[13579][26])|(?:[2468][048]|0[48]))))(?:(?:(?:09|04|06|11)(?:0[1-9]|1[0-9]|2[0-9]|30))|(?:(?:01|03|05|07|08|10|12)(?:0[1-9]|1[0-9]|2[0-9]|3[01]))|(?:02(?:0[1-9]|1[0-9]|2[0-9]))))|(?:[0-9]{4}(?:(?:(?:09|04|06|11)(?:0[1-9]|1[0-9]|2[0-9]|30))|(?:(?:01|03|05|07|08|10|12)(?:0[1-9]|1[0-9]|2[0-9]|3[01]))|(?:02(?:[01][0-9]|2[0-8])))))(?:0[0-9]|1[0-9]|2[0-3])(?:[0-5][0-9]){2}

See demo

Note you are using matches() method that forces a match on the whole string, so it seems the $ anchor is not necessary.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • I am glad it worked for you. If you find my answer helpful, please consider also upvoting. Are you sure you do not need a code example with `SimpleDateFormat`? I can provide it as well. – Wiktor Stribiżew Jun 30 '15 at 08:58
  • You should have suggested SimpleDateFormat in the first place. Anyway, I have written an answer with SimpleDateFormat example. – nhahtdh Jun 30 '15 at 09:15
  • @nhahtdh: Again you are telling people what to use. Please respect the freedom of choice. – Wiktor Stribiżew Jun 30 '15 at 09:17
  • 1
    Between an approach which is hardly maintainable, and an approach which has been thoroughly tested provided by the API and simple to use, of course, I would recommend the simple approach to avoid reinventing the wheel. – nhahtdh Jun 30 '15 at 09:38
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Apr 12 '18 at 20:34
1

If you don't need to deal with leap second (which is not supported in Sun/Oracle JDK), use SimpleDateFormat with setLenient to false to disable lenient parsing. This is better than writing an unmaintainable regex to parse it.

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SO31132861 {
    public static void main(String[] args) {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        df.setLenient(false);

        System.out.println(tryParse(df, "20160630231110"));
        System.out.println(tryParse(df, "20150228231100"));
        System.out.println(tryParse(df, "20160229231100"));

        System.out.println(tryParse(df, "21000229231100")); // 29th Feb on non-leap year 2100
        System.out.println(tryParse(df, "20160631231110")); // 31st Jun invalid day
        System.out.println(tryParse(df, "20160229231160")); // Second > 59
        System.out.println(tryParse(df, "20150229231100")); // 29th Feb on non-leap year 2015
        System.out.println(tryParse(df, "20150228241100")); // Hour > 23
    }

    private static Date tryParse(DateFormat df, String s) {
        try {
            return df.parse(s);
        } catch (ParseException e) {
            return null;
        }
    }
}

If you need leap second, you might want to take a look at this answer: Are leap seconds catered for by Calendar?

Community
  • 1
  • 1
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
  • 1
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Apr 12 '18 at 20:34
1

No need for regex

Java has an industry-leading set of classes for date-time handling, found in the java.time package. Let them handle parsing of your input strings rather than messing with regex.

java.time

The modern approach uses the java.time classes that supplanted the troublesome legacy date-time classes (Date, Calendar, SimpleDateFormat).

Define a formatting pattern to match your input strings.

String input = "20180123123456" ;  // yyyymmddhhmmss
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuuMMddHHmmss" ) ;

Parse as a LocalDateTime because your input lacks any indication of time zone or offset-from-UTC.

LocalDateTime ldt = LocalDateTime.parse( input , f ) ;

ldt.toString(): 2018-01-23T12:34:56

To trap for invalid input, catch DateTimeParseException.

String input = "20180123123456" ; 
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuuMMddHHmmss" ) ;
LocalDateTime ldt = null;
try {
    ldt = LocalDateTime.parse( input , f );
} catch ( DateTimeParseException e ) {
    System.out.println( "ERROR - invalid input for date-time. input: " + input ) ;
    e.printStackTrace();  // Handle invalid input.
}

By the way, be aware that without the context of a time zone or offset-from-UTC, your input string and the LocalDateTime do not represent a specific moment, and are not a point on the timeline. They represent potential moments along a range of about 26-27 hours (the min/max range of time zone offsets).


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
-2

Spent some time elaborating it, but it's pretty much straightforward:

(\d{4}(0[0-9]|1[0-2])([0-2][0-9]|3[0-1])([0-1][0-9]|2[0-4])(([0-5][0-9]){2}))

I think this is what you're looking for. You can test it in regexr

Cheers!

Keews
  • 249
  • 2
  • 15