how to do regex date format change? - javascript

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;
if(dateString.match(dateformat)){
let operator = dateString.split('/');
console.log(operator)
}

Don't. Use Date.parse() instead.

For month: ^0{1}[1-9]$|^[1-9]{1}$|^1[012]{1}$
The first part is with 0, the second part is without 0, and the last one is for 10, 11 and 12.
For days: ^0{1}[1-9]{1}$|^[1-9]{1}$|^[12]{1}[0-9]{1}$|^3[01]{1}$
The first one is for days with from 1-9 starting with 0 and the second one is for the same but without the 0.
About the if the max day is 31, 30 or 28 I would use javascript for that.

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:
(0[1-9]|[12]\d|30)
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:
(0[1-9]|[12]\d|30|[1-9])
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.

Related

Verify date with regular expressions [duplicate]

This question already has answers here:
How to write regex to validate dates?
(7 answers)
Closed 7 years ago.
date format is 2015/04/25
I am trying
^\d{4}\/\d{2}\/\d{2}$
And its working fine, But i want to validate that the month should b less then 12 and date less then 31
I had tried this
^\d{4}\/(\d{2}\<[12])\/\d{2}$
But it is not working.
PS: I am very noob in regular expressions.
You can use
^\d{4}\/(0\d|1[0-2])\/([0-2]\d|3[01])$
Explanation:
\d{4} any four digits
(0\d|1[0-2]) 0(any digit) or 1(0 to 2) i.e 00 to 09 or 10-12
([0-2]\d|3[01]) (0 to 2)(any digit) or 3(0 or 1) i.e 00 to 29 or 30 or 31
Edit1: If you want to match from 01-12 only for months and 01-31 only for day (without 00) you can use :
^\d{4}\/(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01])$
Edit2: If you want strict validation of dates use explode and checkdate.. as suggested by #Wayne.. since it also includes validation of leap years.
See Demo
As jeroen pointed out above, the best solution would be to use a combination of the functions explode and checkdate. A regex isn't going to catch dates that never occurred.
$exploded = explode("/", $date);
if(checkdate($exploded[1], $exploded[2], $exploded[0])){
//Valid date.
}
PS, you might also want to check the number of elements in the $exploded array, seeing as you're expecting three strings.
here is extended version of the same principle shown by used #karthik manchala
^((\d{4}\/(0[469]|11)\/(0[1-9]|1\d|30))|(\d{4}\/(0[13578]|1[02])\/([0-2]\d|3[01]))|(\d{4}\/(02)\/(0[1-9]|[12]\d)))$
it will filter as well 30 vs 31 and everything above 29 for february. It will not recognise when to use 28 and 29 in february though.
If you want to capture leap year you can do it easily if it is recent date or date in near future as it is divisible by 4, you can capture 2000, 2004, 2008, 2012 etc. but the rule is not consistent.

Pad day and time in MomentJS without extra logic

I have a date formatted in Moment.JS but when I call
currentDay.month()
//Or
currentDay.date()
I get a 1 digit number (for example Jan 1st would be 0 for month and 1 for day). I need to get this with a leading 0 for date and month if less than 10. I can do this with something like...
currentDay.date() >= 10 ? currentDay.date() : '0'+currentDay.date()
But I was looking for something a bit nicer. Can I do this easily with MomentJS? I don't see anything in docs.
You can do this, eg for the month, with
moment().format('MM')

Calculate actual number of days from series of date ranges

I need to calculate the actual number of days between a number of date ranges.
eg:
2014-01-01 to 2014-01-04 is 4 days
2014-01-05 to 2014-01-06 is 2 days
while
2014-02-01 to 2014-02-03 3 days
with
2014-02-03 to 2014-02-05 3 days
is a total of 5 days
an added complication is that during a month there will be some gaps between date ranges and or overlapping date ranges to be taken into consideration
any ideas guys.
ability to do the calc using mysql would be great.
Maybe i should have said count the number of days instead of calculate.
I can get the number of days between two date ranges using either mysql or javascript as mentioned below, I think my wheels are coming off with the overlapping date ranges where one range starts before another has finished.
As suggested HERE:
You can use Date objects in Javascript:
var prevTime = new Date(2011,1,1,0,0); // Feb 1, 2011
var thisTime = new Date(); // now
var diff = thisTime.getTime() - prevTime.getTime(); // now - Feb 1
alert(diff / (1000*60*60*24)); // positive number of days
EDIT: I missed you tagged JavaScript, but asked for MySQL
As suggested HERE:
If you are using DATE or DATETIME formatting for your column, you can use:
SELECT DATEDIFF(STR_TO_DATE('2014-01-01', '%Y-%m-%d'),STR_TO_DATE('2014-01-04', '%Y-%m-%d')) AS DAYS
Hope that helps
EDIT2 Here's a nice way to do it in one statement with some logic:
SELECT (CASE
WHEN Start_date1 <= End_date2 THEN
1+DATEDIFF(End_date2, Start_date1)
WHEN Start_date2 <= End_date1 THEN
1+DATEDIFF(End_date1, Start_date2)
ELSE 0
END) AS DAYS
FROM TABLE
The logic is:
Date1 starts before Date2 ends, Start_date1 >= End_date2
OR
Date2 starts before Date1 ends, Start_date2 >= End_date1
If neither is true, they don't overlap.
This little snippet of SQL request code may get you started. It uses DATEDIFF():
SELECT 1+DATEDIFF(MAX(end_date), MIN(start_date)) AS duration_in_days, event_id
FROM event_table
GROUP BY event_id
What's going on here?
First, you've said that the range 21-Aug-14 to 22-Aug-14 is 2 days, but DATEDIFF computes it as 1. So we need to add 1 to it.
Second, the GROUP BY here will aggregate multiple date ranges, if any, for the same event. I have no idea if you're using events; you didn't say. The point here is to show how to aggregate these dates.
Third, if your individual date ranges are non-overlapping, this query won't work correctly. For example, suppose you have these two date ranges
21-Aug-14 to 22-Aug-14
27-Aug-14 to 28-Aug-14
This query will come up with the aggregate range 21-Aug-14 to 28-Aug-14, which is eight days. But you may want to omit the gap 23-Aug to 26-Aug, and only report 4 days. This query won't do that.

what will be the regular expression of date format 'dd-M-y'

what will be the regular expression of date format like '01-Aug-12'.
I have the date format of dd-M-y in asp.net application and want to validate it from asp.net regular expression validator control.
A very basic format check would be:
\d{2}-[A-Za-z]{3}-\d{2}
See for yourself here.
To actually validate, we need a day check like #Brijesh Gandhi suggested and then add a complete month list like this:
([12]\d|0[1-9]|3[0-1])-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{2}
If you want to allow for lowercase months like aug, you can add the case-insensivity modifier ?i: like this...
([12]\d|0[1-9]|3[0-1])-(?i:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{2}
...but that will also allow a month like e.g. aUg - it might be most correct to only allow the first character to be upper- or lowercase.
([12]\d|0[1-9]|3[0-1])-([Jj]an|[Ff]eb|[Mn]ar|[Aa]pr|[Mm]ay|[Jj]un|[Jj]ul|[Aa]ug|[Ss]ep|[Oo]ct|[Nn]ov|[Dd]ec)-\d{2}
See this final version in action here.
Please note that this still will not detect invalid dates like 30-Feb-12. A regexp not accepting those special dates will be very long/ugly. Even using Javascript's Date.parse(...)/new Date(...) will not help detect those as it happily accepts the above mentioned, non-existant date, and return the 1st of March. So to be 100% correct, you need to either do complex coding yourself, or use a library like datejs.
Edit 1: Shortened #Brijesh Gandhi's day check a bit, updated Regexr link.
Edit 2: Remark on correctness.
Why regexp?
I would validate it using
DateTime.TryParse(...)
Anyway a basic form of regex could be
[0-3][0-9]-[A-Z][a-z][a-z]-[0-9][0-9]
which could be better than nothing.
This won't be too elegant, but if you want to use regex to validate dates, it is here:
The regex with explanation
(
(
31-(Jan|Mar|May|Jul|Aug|Oct|Dec)| # months with 31 days
(0[1-9]|[12]\d|30)-(Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)| # months with 30 or 31 days
(0[1-9]|1\d|2[0-8])-Feb # February up to 28th
)
-\d\d # any two digits represent the year
)|
(
29-Feb-([02468][048]|[13579][26]) # February 29th
)
This regex doesn't accept invalid dates like 00-Aug-00, 32-Aug-00 and 29-Feb-01 while accepting valid dates including leap days (29-Feb-04). Note that we assume 00 stands for year 2000, not 1900. So, we accepted 29-Feb-00 as leap day!
In one line:
See it in action:
((31-(Jan|Mar|May|Jul|Aug|Oct|Dec)|(0[1-9]|[12]\d|30)-(Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)|(0[1-9]|1\d|2[0-8])-Feb)-\d\d)|(29-Feb-([02468][048]|[13579][26]))
Case-insensitivity
In Javascript, add an i as second parameter:
var re = new RegExp(regexStr, "i");
In ASP.NET, use RegexOptions.IgnoreCase:
Regex re = new Regex(regexStr,RegexOptions.IgnoreCase);
Regular Expression is definitely not the way to go here. We could do a simple Date.Parse which returns NaN if the date is not valid.
var myDate = '01-Aug-12​';
var isValidDate = !isNaN( Date.parse( myDate ));
try this regex
([1-2][0-9]|[0][1-9]|[3][0-1])-[a-zA-Z][A-Za-z][a-zA-Z]-[0-9][0-9]
00-aug-12 is not valid date according this regex [0-3][0-9]-[A-Z][a-z][a-z]-[0-9][0-9]
Here is regex for every combination of the date format dd-MMM-yy:
[0123][0-9]-[JFMASOND][aepuco][nbrylgptvc]-[0-9][0-9]
Note how the month part is overly strict, while you may still be able to supply an invalid date. Maybe it is better to try to parse the date and check whether it is valid.

regex javascript to add to expression

I have to write a few regexes. I did all except the following. I don't know how to add something via regex only.
Change this  9/28/2005  to  09.28.2005  (Am able to replace slashes with period but how to add leading zero to 9)
Change September 21, 2006 to 21. September 2006 (am able to replace , with . but how to change the order?)
Change 5:00 PM to i7:00 Uhr   (12 to 24 hour)?
1st Case (padding with zero):
result = subject.replace(/\b(\d)(?=[\/.])/ig, "0$1");
2nd Case (change order):
result = subject.replace(/\b(january|february|march|april|may|june|july|august|september|october|november|december) +(\d{2}), +(\d{2,4})\b/ig, "$2. $1 $3");
3rd case (12-24 hr)
As JavaScript RegEx engine does not support If-Then-Else Conditionals. So, it is hard and time-taking job to create a pure RegEx pattern for that purpose.
Hope this helps.
Just do the math manually... e.g. make a function GetTimeZoneOffset and go from there...
Return the timezone difference between UTC and Local Time:
var d = new Date()
var n = d.getTimezoneOffset();
The resulting value of n will be: 240
Add the difference and viola you have a real date which you can format what way you want..

Categories

Resources