[Fixed] how to do regex date format change?


Currently below regex is working fine with dates but I want it to accept those date and month also which has single digit. How can I do that?

Regex should accept below formats also:

’11/4/2021′ or ‘1/4/2021’ or ‘1/04/2021’

dateString = '11/04/2021'

let dateformat = /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([1][26]|[2468][048]|[3579][26])00))))$/g;      
    let operator = dateString.split('/');     


You are able to achieve the requested by adding to the 8th group an OR statement with the 1 to 9 characters. That’s for the days. The same goes for the months.

Let me give you an example.
Your matching group for the days right now is looking like this:


Which means that you accept all numbers which start with 0 and a digit from 1 to 9 afterwards, a number starting with either 1 or 2 and any digit afterwards, or 30.

In order to accept the digits from 1 to 9 you have to add another condition to your matching group and that is the 1 to 9 digits. So your group will look something like the following:


This is the most basic thing you can do. There are plenty of ways to optimize this regex and do it in a better way. You can think about the 31st day of the month, since right now it is not capturing it.

The same way I shown in the example for the days’ matching group, you can do it for the months’ matching group.

Leave a Reply

(*) Required, Your email will not be published