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.
Related
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.
I'm trying to find the difference between today and a date in the future (number of days) using moment.js.
But the response is always off by 1-2 days.
For instance, trying to find the # of days between today (15 June) and 11th July gives me 25 days whereas it should be 27 days.
Here's what I am using
moment(expiryDate).diff(moment(), 'days');
expiryDate is a string of the format YYYY-MM-DD
I am assuming the difference is because the dates themselves are not included? But nothing in the moment.js document suggests this. Neither did I find anything by which I can tell the library to calculate the difference inclusive of the dates.
This should do the trick
console.log(
moment("2020-07-11", 'YYYY-MM-DD').diff(moment("2020-06-15", 'YYYY-MM-DD'),"days")
) // outputs 26 (which is correct)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>
I'm trying to get a moment object which matches July 8th 2021 from this code:
moment('121 07 08', 'CYY MM DD')
I'm trying to use century since the value is coming from a legacy database and it seems like moment.js doesn't support it. This is not the only instance of it, so I'm trying to figure out the best way to handle it.
Any ideas?
There isn't a century modifier in moment, but 2 digit years where the values are less than 68 are assumed to be in the year 2000, per the docs:
Parsing two digit years
By default, two digit years above 68 are assumed to be in the 1900's
and years 68 or below are assumed to be in the 2000's. This can be
changed by replacing the moment.parseTwoDigitYear method.
C is ignored so it will see the 12 as the 2-digit year. Remove the C and the 1 and you're set.
console.log(moment('21 07 08', 'YY MM DD').format('MMMM Do YYYY'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment-with-locales.min.js"></script>
This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
Hi I am trying to construct a javascript date object with a string, but it keeps contructing the wrong day. It always constructs a day that is one day behind. Here is my code
var date = new Date('2006-05-17');
The date i want to get is
Wednesday May 17 2006 00:00:00 GMT-0700 (PDT)
But instead I get
Tue May 16 2006 17:00:00 GMT-0700 (PDT)
When you pass dates as a string, the implementation is browser specific. Most browsers interpret the dashes to mean that the time is in UTC. If you have a negative offset from UTC (which you do), it will appear on the previous local day.
If you want local dates, then try using slashes instead, like this:
var date = new Date('2006/05/17');
Of course, if you don't have to parse from a string, you can pass individual numeric parameters instead, just be aware that months are zero-based when passed numerically.
var date = new Date(2006,4,17);
However, if you have strings, and you want consistency in how those strings are parsed into dates, then use moment.js.
var m = moment('2006-05-17','YYYY-MM-DD');
m.format(); // or any of the other output functions
What actually happens is that the parser is interpreting your dashes as the START of an ISO-8601 string in the format "YYYY-MM-DDTHH:mm:ss.sssZ", which is in UTC time by default (hence the trailing 'Z').
You can produce such dates by using the "toISOString()" date function as well.
http://www.w3schools.com/jsref/jsref_toisostring.asp
In Chrome (doesn't work in IE 10-) if you add " 00:00" or " 00:00:00" to your date (no 'T'), then it wouldn't be UTC anymore, regardless of the dashes. ;)
Remove the prepending zero from "05"
I have an old web app where Javascript is used to validate some dates. Users usually use 2-digit years and I recently discovered it was evaluating 00 as 1900 instead of 2000
if (new Date(tb[0].value) > new Date(tb[1].value)){
alert('Starting date must come before the ending date');
tb[0].focus();
return false;
}
Entering 1/1/99 in the first box and 1/1/00 in the 2nd will cause an error message saying the start date has to be before the end date because 99 is evaluating at 1999 while 00 is evaluating at 1900.
Of course, Users can get around this using 4-digit years, but I still want to know what can be done to get Javascript to evaluate 2-digit years correctly.
So my question is, how can I get Javascript to evaluate 00 as 2000 and not 1900?
It does that because the language was created in the 1990's (and in a hurry). You can use getFullYear() and setFullYear() to handle years in a non-goofy way.
What I've done is write some code to check for year values less than 100, and if it's greater than 90 (or something similarly appropriate, depending on the situation) assume it's in the 20th century, otherwise assume the 21st.
And #Rachel no there's no way to tell the runtime library to behave differently, at least not any standardized way. That's just how the Date code works.
The simplest way is just to accept it does it that way and check for it.
if (date.getFullYear() < 1970) {
date.setFullYear(date.getFullYear() + 100);
}
1970 is of course just an example value as you have to have a sensible break point. You may want to do that as current year - x instead of a constant of course.
Chrome actually handles this correctly, but IE and Firefox (at least) do not. Here's my solution:
var x = new Date(input); //parse the date initially
if (x!="Invalid Date") {
var n = input.split(/[/-]/); //regex to look for / or - delimited dates
if (n[2].length == 2) //if the input has a 2 digit year
{
var y = x.getFullYear();
if (y < 1950) //and the parser decided it's before 1950
x.setFullYear(y + 100); //add a century
}
}
output = dateToShortString(x); //custom function to standardize formatting
The way I've done this in the past is to select an arbitrary year that lets the code assume that 2 digit years prior to that arbitrary year are in the 1900's, while years after that are in the 2000's. For an accounting app I had to make Y2K compliant, if I recall correctly, I chose 1940. So transactions between 40-99 were 1940-1999, and transactions 00-39 were 2000-2039.
is there a reason you couldn't do something along these lines?
The big assumption being that if the user is entering a 2 digit year that its probably not intended to be over 100 years in the past.
myDate('2-1-00');
function myDate(date) {
let today = new Date();
date = new Date(date.split('-').join('/'));
if ((today.getFullYear() - date.getFullYear()) >= 100) {
date.setFullYear(date.getFullYear() + 100);
}
alert(date);
}