VOOZH about

URL: https://www.geeksforgeeks.org/dsa/validate-traditional-datetime-format-yyyy-mm-dd-hhmmss/

⇱ Validate Traditional DateTime Format (YYYY-MM-DD HH:MM:SS) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Validate Traditional DateTime Format (YYYY-MM-DD HH:MM:SS)

Last Updated : 23 Jul, 2025

Given some Traditional Date Time Formats, the task is to check if they are valid or not using regular expressions. Rules for the valid format are:

  • It should contain only digits (0 - 9) and a few words like (SEPTEMBER, Sep, SEP).
  • It can only contain a few special characters like ":", and "-".
  • It can only contain one white space.

Examples:

Input: "2023-01-01 01:01:01"
Output: True

Input: "12/07/1998 12:00"
Output: False

Approach: The problem can be solved based on the following idea:

Create a regex pattern to validate the number as written below:   
regex = "^([0-9]{4})-((01|02|03|04|05|06|07|08|09|10|11|12|(?:J(anuary|u(ne|ly))|February|Ma(rch|y)|A(pril|ugust)|(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)|(JANUARY|FEBRUARY|MARCH|APRIL|MAY|JUNE|JULY|AUGUST|SEPTEMBER|OCTOBER|NOVEMBER|DECEMBER)|(September|October|November|December)|(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)|(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)))|(january|february|march|april|may|june|july|august|september|october|november|december))-([0-3][0-9])\s([0-1][0-9]|[2][0-3]):([0-5][0-9]):([0-5][0-9])$"

Where,

  • ^ : Starting of the string.
  • [0 - 9] {4} : 4 digits should be there
  • \ : One of them should be present. 
  • $ : End of the string.

Follow the below steps to implement the idea:

  • Create a regex expression for the Traditional DateTime Format.
  • Use Pattern class to compile the regex formed.
  • Use the matcher function to check whether the Format is valid or not.
  • If it is valid, return true. Otherwise, return false.

Below is the implementation of the above approach:


Output
true
true
false
false
false

Time Complexity: O(N) for each testcase, where N is the length of the given string. 
Auxiliary Space: O(1)  

Related Articles:

Comment