Javascript Date allows invalid data (e.g. Feb 30th) [duplicate] - javascript

This question already has answers here:
How to validate a date?
(11 answers)
Closed 6 years ago.
How to validate a date? I mean not the format, but the logic.
For example: Feb 30th is not a valid date.
var date = new Date("2015-02-29T13:02:49.073Z"); // 2015 Feb 29th does not exist
console.log(date.toISOString());
Returns 2015-03-01T13:02:49.073Z (March 1st).
But I want a information that this date (input) is not valid.
Edit:
Tested in Chrome. Firefox returns "invalid date". But not on parsing.
Only when the date is used (e.g. toISOString()) an exception is thrown.
try
{
var date = new Date("2015-02-29T13:02:49.073Z");
console.log(date.toISOString());
}
catch(e)
{
console.log("error: " + e.message);
}
Firefox:
invalid date
Chrome:
(nothing, just switched to the next date.)
Summary: It is browser-dependent. So, not recommended to use.
jsfiddle example

I use this function to check whether a date is valid or not:
function isValidDate(year, month, day) {
month = month - 1;
var d = new Date(year, month, day);
if (d.getFullYear() == year && d.getMonth() == month && d.getDate() == day) {
return true;
}
return false;
}

The easiest thing I can think of, is to convert the parsed date to ISO string and compare it to the original input:
var input = "2015-02-29T13:02:49.073Z"
var date = new Date(input);
var isValid = (input === date.toISOString());

I wrote small function for you:
function check_date(str){
try{
return str == new Date(str).toISOString()
}catch(e){
return false;
}
}
Try this
console.log(check_date('2015-02-01T13:02:49.073Z'));
console.log(check_date('2015-02-35T13:02:49.073Z'));
console.log(check_date('2015-02-29T13:02:49.073Z'));
https://jsfiddle.net/8o040ctr/

I've found that behavior rather amusing. I used to just convert the input to a date (as you've done), then update the text in the textbox to show the date as interpreted by JavaScript so the user would see the resulting (valid) date.
Luckily, we can do much better now. Moment.js is a fantastic library for dealing with date/time values in JavaScript. It's sure made life a lot easier for me!
http://momentjs.com/

If you pass a string that starts with 'YYYY-MM' format, like you have in the question, you could use this function:
function makeDate(s) {
var date = new Date(s);
if (date.toISOString(date).substr(0,7) != s.substr(0,7)) throw "Invalid date";
return date;
}
dt = makeDate('2015-02-29T13:02:49.073Z');
This makeDate function would replace the plain new Date(...) call, but will also throw an error in Chrome when it is passed an invalid date string.

Dates in browsers are always very tricky, I suggest you to use a js lib like moment: http://momentjs.com/
then you can use .isValid() method for ex.:
moment('03:55', 'HH:mm').isValid();
moment('2012-05-25', 'YYYY-MM-DD').isValid();
moment('2015-02-29T13:02:49.073Z', "YYYY-MM-DDTHH:mm:ss", true).isValid();

Related

What is an elegant way to check if a date is valid in JavaScript? [duplicate]

What is an easy way to check if a value is a valid date, any known date format allowed.
For example I have the values 10-11-2009, 10/11/2009, 2009-11-10T07:00:00+0000 which should all be recognized as date values, and the values 200, 10, 350, which should not be recognized as a date value. What is the simplest way to check this, if this is even possible? Because timestamps would also be allowed.
2015 Update
It is an old question but other new questions like:
How to validate if a string is a valid date in js
get closed as duplicates of this one, so I think it's important to add some fresh info here. I'm writing it because I got scared thinking that people actually copy and paste some of the code posted here and use it in production.
Most of the answers here either use some complex regular expressions that match only some very specific formats and actually do it incorrectly (like matching January 32nd while not matching actual ISO date as advertised - see demo) or they try to pass anything to the Date constructor and wish for the best.
Using Moment
As I explained in this answer there is currently a library available for that:
Moment.js
It is a library to parse, validate, manipulate, and display dates in JavaScript, that has a much richer API than the standard JavaScript date handling functions.
It is 12kB minified/gzipped and works in Node.js and other places:
bower install moment --save # bower
npm install moment --save # npm
Install-Package Moment.js # NuGet
spm install moment --save # spm
meteor add momentjs:moment # meteor
Using Moment you can be very specific about checking valid dates. Sometimes it is very important to add some clues about the format that you expect. For example, a date such as 06/22/2015 looks like a valid date, unless you use a format DD/MM/YYYY in which case this date should be rejected as invalid. There are few ways how you can tell Moment what format you expect, for example:
moment("06/22/2015", "MM/DD/YYYY", true).isValid(); // true
moment("06/22/2015", "DD/MM/YYYY", true).isValid(); // false
The true argument is there so the Moment won't try to parse the input if it doesn't exactly conform to one of the formats provided (it should be a default behavior in my opinion).
You can use an internally provided format:
moment("2015-06-22T13:17:21+0000", moment.ISO_8601, true).isValid(); // true
And you can use multiple formats as an array:
var formats = [
moment.ISO_8601,
"MM/DD/YYYY :) HH*mm*ss"
];
moment("2015-06-22T13:17:21+0000", formats, true).isValid(); // true
moment("06/22/2015 :) 13*17*21", formats, true).isValid(); // true
moment("06/22/2015 :( 13*17*21", formats, true).isValid(); // false
See: DEMO.
Other libraries
If you don't want to use Moment.js, there are also other libraries:
XDate
DateJS
2016 Update
I created the immoment module that is like (a subset of) Moment but without surprises caused by mutation of existing objects (see the docs for more info).
2018 Update
Today I recommend using Luxon for date/time manipulation instead of Moment, which (unlike Moment) makes all object immutable so there are no nasty surprises related to implicit mutation of dates.
More info
See also:
Managing Dates and Times Using Moment.js by Jay Raj
Working with JavaScript Dates Using Moment.js by Bradley Holbrook
A series of articles by Rob Gravelle on JavaScript date parsing libraries:
A Roundup of Popular JavaScript Date Parsing Libraries: Moment.js
A Roundup of Popular JavaScript Date Parsing Libraries: Datejs
A Roundup of Popular JavaScript Date Parsing Libraries: XDate
Bottom line
Of course anyone can try to reinvent the wheel, write a regular expression (but please actually read ISO 8601 and RFC 3339 before you do it) or call buit-in constructors with random data to parse error messages like 'Invalid Date' (Are you sure this message is exactly the same on all platforms? In all locales? In the future?) or you can use a tested solution and use your time to improve it, not reinvent it. All of the libraries listed here are open source, free software.
This is how I solved this problem in an app I'm working on right now:
updated based on feedback from krillgar:
var isDate = function(date) {
return (new Date(date) !== "Invalid Date") && !isNaN(new Date(date));
}
Would Date.parse() suffice?
See its relative MDN Documentation page.
Date.parse returns a timestamp if string date is valid. Here are some use cases:
// /!\ from now (2021) date interpretation changes a lot depending on the browser
Date.parse('01 Jan 1901 00:00:00 GMT') // -2177452800000
Date.parse('01/01/2012') // 1325372400000
Date.parse('153') // NaN (firefox) -57338928561000 (chrome)
Date.parse('string') // NaN
Date.parse(1) // NaN (firefox) 978303600000 (chrome)
Date.parse(1000) // -30610224000000 from 1000 it seems to be treated as year
Date.parse(1000, 12, 12) // -30610224000000 but days and month are not taken in account like in new Date(year, month,day...)
Date.parse(new Date(1970, 1, 0)) // 2588400000
// update with edge cases from comments
Date.parse('4.3') // NaN (firefox) 986248800000 (chrome)
Date.parse('2013-02-31') // NaN (firefox) 1362268800000 (chrome)
Date.parse("My Name 8") // NaN (firefox) 996616800000 (chrome)
new Date(date) === 'Invalid Date' only works in Firefox and Chrome. IE8 (the one I have on my machine for testing purposes) gives NaN.
As was stated to the accepted answer, Date.parse(date) will also work for numbers. So to get around that, you could also check that it is not a number (if that's something you want to confirm).
var parsedDate = Date.parse(date);
// You want to check again for !isNaN(parsedDate) here because Dates can be converted
// to numbers, but a failed Date parse will not.
if (isNaN(date) && !isNaN(parsedDate)) {
/* do your work */
}
Does not work consistently, watch out!
isDate('Leyweg 1') returns true on Chrome (Firefox returns false) 🤔
Read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse (Date.parse is called under the hood when invoking like so: new Date(someDateString).
Original answer:
function isDate(dateStr) {
return !isNaN(new Date(dateStr).getDate());
}
This will work on any browser since it does not rely on "Invalid Date" check.
This will work with legacy code before ES6.
This will work without any library.
This will work regardless of any date format.
This does not rely on Date.parse which fails the purpose when values like "Spiderman 22" are in date string.
This does not ask us to write any RegEx.
None of the answers here address checking whether the date is invalid such as February 31. This function addresses that by checking if the returned month is equivalent to the original month and making sure a valid year was presented.
//expected input dd/mm/yyyy or dd.mm.yyyy or dd-mm-yyyy
function isValidDate(s) {
var separators = ['\\.', '\\-', '\\/'];
var bits = s.split(new RegExp(separators.join('|'), 'g'));
var d = new Date(bits[2], bits[1] - 1, bits[0]);
return d.getFullYear() == bits[2] && d.getMonth() + 1 == bits[1];
}
How about something like this? It will test if it is a Date object or a date string:
function isDate(value) {
var dateFormat;
if (toString.call(value) === '[object Date]') {
return true;
}
if (typeof value.replace === 'function') {
value.replace(/^\s+|\s+$/gm, '');
}
dateFormat = /(^\d{1,4}[\.|\\/|-]\d{1,2}[\.|\\/|-]\d{1,4})(\s*(?:0?[1-9]:[0-5]|1(?=[012])\d:[0-5])\d\s*[ap]m)?$/;
return dateFormat.test(value);
}
I should mention that this doesn't test for ISO formatted strings but with a little more work to the RegExp you should be good.
Use Regular expression to validate it.
isDate('2018-08-01T18:30:00.000Z');
isDate(_date){
const _regExp = new RegExp('^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?(Z)?$');
return _regExp.test(_date);
}
By referring to all of the above comments, I have come to a solution.
This works if the Date passed is in ISO format or need to manipulate for other formats.
var isISO = "2018-08-01T18:30:00.000Z";
if (new Date(isISO) !== "Invalid Date" && !isNaN(new Date(isISO))) {
if(isISO == new Date(isISO).toISOString()) {
console.log("Valid date");
} else {
console.log("Invalid date");
}
} else {
console.log("Invalid date");
}
You can play here on JSFiddle.
Here is an improved function that uses only Date.parse():
function isDate(dateToTest) {
return isNaN(dateToTest) && !isNaN(Date.parse(dateToTest)));
}
Note: Date.parse() will parse numbers: for example Date.parse(1) will return a date. So here we check if dateToTest is not a number then if it is a date.
I know it's an old question but I faced the same problem and saw that none of the answers worked properly - specifically weeding out numbers (1,200,345,etc..) from dates, which is the original question. Here is a rather unorthodox method I could think of and it seems to work. Please point out if there are cases where it will fail.
if(sDate.toString() == parseInt(sDate).toString()) return false;
This is the line to weed out numbers. Thus, the entire function could look like:
function isDate(sDate) {
if(sDate.toString() == parseInt(sDate).toString()) return false;
var tryDate = new Date(sDate);
return (tryDate && tryDate.toString() != "NaN" && tryDate != "Invalid Date");
}
console.log("100", isDate(100));
console.log("234", isDate("234"));
console.log("hello", isDate("hello"));
console.log("25 Feb 2018", isDate("25 Feb 2018"));
console.log("2009-11-10T07:00:00+0000", isDate("2009-11-10T07:00:00+0000"));
I feel none of the answers correctly understood what the OP asked. The issue here is that JavaScript can parse any number as a valid date, since the Date object can parse a string like '3000' as the year and will return a valid Date instance:
new Date('3000')
> Wed Jan 01 3000 02:00:00 GMT+0200 (Eastern European Standard Time)
To solve this, we can use the Day.js library's parsing method in strict mode by passing in a third argument. It's documented in their String + Format page. In order for parsing to work based on a format, we must also enable the CustomParseFormat plugin. I'm assuming you can use ESM imports here or have a compiler like Webpack set up
import dayjs from 'dayjs'
import formatParser from 'dayjs/plugin/customParseFormat'
dayjs.extend(formatParser)
dayjs('3000', 'YYYY-MM-DD', true).isValid()
> false
I would do this
var myDateStr= new Date("2015/5/2");
if( ! isNaN ( myDateStr.getMonth() )) {
console.log("Valid date");
}
else {
console.log("Invalid date");
}
Play here
is it fine to check for a Date related function is available for the object to find whether it is a Date object or not ?
like
var l = new Date();
var isDate = (l.getDate !== undefined) ? true; false;
This callable function works perfectly, returns true for valid date.
Be sure to call using a date on ISO format (yyyy-mm-dd or yyyy/mm/dd):
function validateDate(isoDate) {
if (isNaN(Date.parse(isoDate))) {
return false;
} else {
if (isoDate != (new Date(isoDate)).toISOString().substr(0,10)) {
return false;
}
}
return true;
}
I think the most straight forward solution would be
Date.parse(yourDate) > 0 ? true : false;
If it is not a valid date, it will be NaN, which is not greater than 0.
Here's a minimalist version.
var isDate = function (date) {
return!!(function(d){return(d!=='Invalid Date'&&!isNaN(d))})(new Date(date));
}
Ok, this is an old question, but I found another solution while checking the solutions here. For me works to check if the function getTime() is present at the date object:
const checkDate = new Date(dateString);
if (typeof checkDate.getTime !== 'function') {
return;
}
i find this solution very good:
const DateTime = require('luxon').DateTime;
isDateValid(stringDate) {
let date = DateTime.fromFormat(stringDate, 'd-M-y');
if (date.invalid === null) {
return date.toJSDate();
}
date = DateTime.fromFormat(stringDate, 'd,M,y');
if (date.invalid === null) {
return date.toJSDate();
}
date = DateTime.fromFormat(stringDate, 'y-M-d');
if (date.invalid === null) {
return date.toJSDate();
}
date = DateTime.fromFormat(stringDate, 'y,M,d');
if (date.invalid === null) {
return date.toJSDate();
}
date = DateTime.fromFormat(stringDate, 'y.M.d');
if (date.invalid === null) {
return date.toJSDate();
}
date = DateTime.fromFormat(stringDate, 'd.M.y');
if (date.invalid === null) {
return date.toJSDate();
}
date = DateTime.fromFormat(stringDate, 'y/M/d');
if (date.invalid === null) {
return date.toJSDate();
}
date = DateTime.fromFormat(stringDate, 'd/M/y');
if (date.invalid === null) {
return date.toJSDate();
}
return false;
}
isDateValid('30.12.86'); //true
isDateValid('30/12/86'); //true
isDateValid('86-12-40'); //false
and you can easily add more formats
I believe this is the simplest working answer for date that contains only numbers:
var rst = Date.parse(sDate.replaceAll(" ",""));
if(rst===NaN) console.log("not a date");
else console.log("a great date")
By removing spaces you detect values like "hello 2" that are taken as a date.
For the dates that contain strings like day name or month name ... I believe it is about string validation.
This is how I end up doing it. This will not cover all formats.
You have to adjust accordingly. I have control on the format, so it works for me
function isValidDate(s) {
var dt = "";
var bits = [];
if (s && s.length >= 6) {
if (s.indexOf("/") > -1) {
bits = s.split("/");
}
else if (s.indexOf("-") > -1) {
bits = s.split("-");
}
else if (s.indexOf(".") > -1) {
bits = s.split(".");
}
try {
dt = new Date(bits[2], bits[0] - 1, bits[1]);
} catch (e) {
return false;
}
return (dt.getMonth() + 1) === parseInt(bits[0]);
} else {
return false;
}
}
This function verifies that the input string in the format m/d/yyyy or mm/dd/yyyy can be converted to a date and that the date is a valid date matching the input string. Add more conditional checks to verify additional formats.
/**
* Verify if a string is a date
* #param {string} sDate - string that should be formatted m/d/yyyy or mm/dd/yyyy
* #return {boolean} whether string is a valid date
*/
function isValidDate(sDate) {
let newDate = new Date(sDate);
console.log(sDate + " date conversion: " + newDate);
let isDate = (!isNaN(newDate.getTime()));
console.log(sDate + " is a date: " + isDate);
if (isDate) {
let firstSlash = sDate.indexOf("/");
let secondSlash = sDate.indexOf("/",firstSlash+1);
let originalDateString = parseInt(sDate.slice(0,firstSlash),10) + "/" + parseInt(sDate.slice(firstSlash+1,secondSlash),10) + "/" + parseInt(sDate.slice(secondSlash+1),10);
let newDateString = (newDate.getMonth()+1) + "/" + (newDate.getDate()) + "/" + (newDate.getFullYear());
isDate = (originalDateString == newDateString);
console.log(originalDateString + " matches " + newDateString + ": " + isDate);
}
return isDate;
}
Here is what one could use to validate that the input is a number or a string that can be converted to a date object.
It covers the following cases:
catching whatever input leads to "Invalid Date" date constructor result;
catching the cases where the date is "valid" from technical point of view, but it is not valid from business logic point of view, like
new Date(null).getTime(): 0
new Date(true).getTime(): 1
new Date(-3.14).getTime(): -3
new Date(["1", "2"]).toDateString(): Tue Jan 02 2001
new Date([1, 2]).toDateString(): Tue Jan 02 2001
function checkDateInputValidity(input, lowerLimit, upperLimit) {
// make sure the input is a number or string to avoid false positive correct dates:
if (...) {
return false
}
// create the date object:
const date = new Date(input)
// check if the Date constructor failed:
if (date.toDateString() === 'Invalid Date') {
return false
}
// check if the Date constructor succeeded, but the result is out of range:
if (date < new Date(lowerLimit) || date > new Date(upperLimit)) {
return false
}
return true
}
// const low = '2021-12-31T23:59:59'
// const high = '2025-01-01T00:00:00'

JavaScript new Date('22/22/2222') convert to a valid date in IE 11

var checkDate = new Date("22/22/2222");
When I check in IE 11 it convert to Wed Oct 22 00:00:00 EDT 2223 so my next line fails
if (checkDate != 'Invalid Date')
How to fix it?
As you've passed in an invalid date format (as far as the ECMA spec is concerned), the browser is free to choose to interpret it how it wishes. It seems IE thinks it can deal with it:
The function first attempts to parse the format of the String according to the rules (including extended years) called out in Date Time String Format (20.3.1.16). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.
If you're going to pass in strange formats, you're either going to need to validate them yourself or use a library that can do so better than the browsers can.
Months and days can "wrap" in JavaScript. One way to test if the date is legal is to see if the output date corresponds to the original input string. If it doesn't, then it wrapped.
function check(inputString) {
var checkDate = new Date(inputString);
// Get month, day, and year parts, assuming
// you don't have them already
var arr = inputString.split('/');
var isMonthWrapped = +arr[0] !== checkDate.getMonth() + 1;
var isDayWrapped = +arr[1] !== checkDate.getDate();
var isYearWrapped = +arr[2] !== checkDate.getFullYear();
console.log("Parts", +arr[0], +arr[1], +arr[2]);
console.log("Results", checkDate.getMonth() + 1, checkDate.getDate(), checkDate.getFullYear());
console.log("Wrapped?", isMonthWrapped, isDayWrapped, isYearWrapped);
var isLegal = checkDate !== 'Invalid Date' && !isMonthWrapped && !isDayWrapped && !isYearWrapped;
document.body.innerHTML += inputString + ': ' + (isLegal ? 'Legal' : 'Illegal') + '<br>';
};
check("22/22/2222");
check("12/12/2222");
I think that moment.js http://momentjs.com/ is a complete and good package about dates.
You could add string date and format.
moment("12/25/1995", "MM/DD/YYYY");
And you could check if date is valid.
moment("not a real date").isValid();
See documentation
http://momentjs.com/docs/#/parsing/string-format/
You should break up your string and parse Each date to integers individually. It will be much safer.
Do something like this
var dateString = "22/22/2222";
dateString.indexOf("/");
var day = parseInt(dateString.slice(0,dateString.indexOf("/")));
dateString = dateString.slice(1+dateString.indexOf("/"), dateString.length);
var month = parseInt(dateString.slice(0,dateString.indexOf("/")))
dateString = dateString.slice(1+dateString.indexOf("/"), dateString.length);
var year = parseInt(dateString);
console.log(day, month, year);
var date = new Date(0);
if(month>12) console.log("hey this is totally not a valid month maaaan!")
date.setDate(day);
date.setMonth(month);
date.setYear(year);
console.log(date);

Javascript: check date in future in dd/mm/yyyy format?

I'm trying to check the users input field to see if it is in the future and if it is in dd/mm/yyyy format but I have no idea why the format part of my code doesn't fire at all! In fact nothing seems to be working on Jsfiddle but at least my "check date in the future" function works locally.
I don't know the correct way of going about this.
to explain this, I've created this FIDDLE
And this is my full javascript code. I need to stay with pure javascript by the way:
function checkdate(){
//var sendDate = document.getElementById('send_year').value + '/' + document.getElementById('send_month').value + '/' + document.getElementById('send_day').value;
var sendDate = document.getElementById('returning_date').value;
sendDate = new Date(Date.parse(sendDate.replace(/-/g,' ')))
today = new Date();
today.setHours(0,0,0,0)
if (sendDate < today) {
//alert('The date can\'t be in the past. Please pick another date.');
document.getElementById('error8').innerHTML = 'The date can\'t be in the past. Please pick another date.';
return false;
}
else
{
document.getElementById('error8').innerHTML = '';
}
if(sendDate.match(/^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])/))
{
alert('works out');
}
}
could someone please advise on this issue?
Thanks in advance.
One problem is that you are trying to run sendDate.match, but sendDate has been converted into a Date object so it does not have a match method.
You should run your regular expression before you convert it to a Date, in validation, you typically check that the input conforms to a format before you run further validation like range validation.
Date strings should always be manually parsed, you should never allow the Date constructor or Date.parse to parse strings (the Date constructor parses strings in exactly the same way Date.parse does).
To parse and validate a date string is fairly straight forward, just parse the string and see if you get a valid date:
/* Parse a string in d/m/y format. Separator can be any non–digit
** Avoid conversion of two digit dates to 20th century
** Returns an invalid Date if string is not a valid date (per ECMA-262)
**
** #param {string} s - Date string to parse
** #returns {Date}
*/
function parseDMY(s) {
var b = s.split(/\D/);
var d = new Date();
d.setHours(0,0,0,0);
d.setFullYear(b[2], --b[1], b[0]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
// Test valid date
document.write(parseDMY('23/01/2016'));
// Test invalid date
document.write('<br>' + parseDMY('35/12/2016'));
Note that this will accept a date like 1/5/16 and treat is as 1 May, 0016. If you want to guarantee that the day and month values have two digits and the year for, then add:
/^\d\d\D\d\d\D\d{4}$/.test(s)
to the validation test at the end. However, I don't like forcing 2 digits for day and month as people don't usually write dates as "01/08/2016", they use "1/8/2016".
First of all, the function needs to be wrapped in <head> (hit the cog in the js tab), otherwise the function can't be found.
But your main problem is that you are using European style of date formatting, so you'll get a "Invalid Date" exception when creating the date. Refer to this question on how to convert it to USA-style and make it available for the Date object (check the reference for all possible uses)
My proposal is:
Date.prototype.fromString = function(str) {
var m = str.match(/([0-9]{2})(-|\/)([0-9]{2})(-|\/)([0-9]{4})/);
if (m == null) {
return null;
}
for (var i = 0; i < m.length; i++) {
if (typeof(m[i]) === 'undefined') {
return null;
};
};
var year = parseInt(m[5]);
var month = parseInt(m[1]) - 1;
var day = parseInt(m[3]);
if (month == 0 || day == 0) {
return null;
}
return new Date(year, month, day);
}
function checkdate(e, obj, errMsgSel){
var sendDate =obj.value;
sendDate = (new Date()).fromString(sendDate);
if (sendDate == null) {
if (e.type == 'blur') {
obj.value = '';
}
return;
}
today = new Date();
today.setHours(0,0,0,0)
if (sendDate < today) {
//alert('The date can\'t be in the past. Please pick another date.');
document.getElementById(errMsgSel).innerHTML = 'The date can\'t be in the past. Please pick another date.';
return false;
}
else
{
document.getElementById(errMsgSel).innerHTML = '';
}
} $(function () {
});
<input onblur="checkdate(event, this, 'error8');" onKeyUp="checkdate(event, this, 'error8');" type='text' name="text1" placeholder='dd/mm/yyyy' id='returning_date'>
<span id='error8' style='color:red;'>format</span> <br><Br>

javascript Date creates strange date when days are greater than what is in the month

I have an input form where the user can choose a date from a calendar, however I also wanted them to be able to type in the date manually
the function validateDate() is called when the user clicks out of the input box
//Make sure valid date is entered into the field, otherwise throw back an error
function validateDate(date) {
var dateObj = new Date(date);
console.log(dateObj.getDate());
if (dateObj == "Invalid Date") {
dateWrongFormat(false);
return false;
}
return dateTimeToString(dateObj, true);
}
problem is: say if the user types in something by accident like "55/02/2014" it converts to "02 Jul 2018" instead of displaying that it is an invalid date (note: this is 4 years past the year they entered).
Is there are simple way to check if the days or month is invalid this or do I have to create my own date-checking system?
EDIT: so it seems like no matter what I type in, it believes it a valid date - even formatting with moment.js. Thanks for the help guys but I have to write my own for this one!
Try using Date.parse. If you do Date.parse("55/02/2014"), it returns NaN.
UPDATE
Something like this-
<script>
function validateDate(date) {
var datems = Date.parse(date);
if (isNaN(datems)) {
dateWrongFormat(false);
return false;
}else{
var dateObj = new Date(date);
return dateTimeToString(dateObj, true);
}
}
</script>
If you are doing stuff with dates, you may find using MomentJS helpful.
In particular, if you construct a moment instance from a string, you can then ask it if it is valid:
moment('55/02/2014').isValid(); // returns false
Try:
function validateDate(date) {
//Format = dd/mm/yyyy
var day=date.split("/")[0];
var month=date.split("/")[1];
var year=date.split("/")[2];
var dateObj = new Date(year, month-1, day);
console.log(dateObj.getDate());
if ((dateObj .getMonth()+1!=month)||(dateObj .getDate()!=day)||(dateObj .getFullYear()!=year)) {
dateWrongFormat(false);
return false;
}
return dateTimeToString(dateObj, true);
}

How to check if input date is equal to today's date?

I have a form input with an id of 'date_trans'. The format for that date input (which is validated server side) can be any of:
dd/mm/yyyy
dd-mm-yyyy
yyyy-mm-dd
yyyy/mm/dd
However, before posting the form, I'd like to check if the date_trans field has a date that is equal to today's date. Its ok if the date taken is the client's date (i.e. it uses js), since I run a double check on the server as well.
I'm totally lost on how to do the date comparrison in jQuery or just plain old javascript. If it helps, I am using the jquery datepicker
A simple date comparison in pure JS should be sufficient:
// Create date from input value
var inputDate = new Date("11/21/2011");
// Get today's date
var todaysDate = new Date();
// call setHours to take the time out of the comparison
if(inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0)) {
// Date equals today's date
}
Here's a working JSFiddle.
for completeness, taken from this solution:
You could use toDateString:
var today = new Date();
var isToday = (today.toDateString() == otherDate.toDateString());
no library dependencies, and looking cleaner than the 'setHours()' approach shown in a previous answer, imho
Try using moment.js
moment('dd/mm/yyyy').isSame(Date.now(), 'day');
You can replace 'day' string with 'year, month, minute' if you want.
function sameDay( d1, d2 ){
return d1.getUTCFullYear() == d2.getUTCFullYear() &&
d1.getUTCMonth() == d2.getUTCMonth() &&
d1.getUTCDate() == d2.getUTCDate();
}
if (sameDay( new Date(userString), new Date)){
// ...
}
Using the UTC* methods ensures that two equivalent days in different timezones matching the same global day are the same. (Not necessary if you're parsing both dates directly, but a good thing to think about.)
Just use the following code in your javaScript:
if(new Date(hireDate).getTime() > new Date().getTime())
{
//Date greater than today's date
}
Change the condition according to your requirement.Here is one link for comparision compare in java script
The following solution compares the timestamp integer divided by the values of hours, minutes, seconds, millis.
var reducedToDay = function(date){return ~~(date.getTime()/(1000*60*60*24));};
return reducedToDay(date1) == reducedToDay(date2)
The tilde truncs the division result (see this article about integer division)
Date.js is a handy library for manipulating and formatting dates. It can help in this situation.
Try this
// method to check date is less than today date
isLessDate(schedule_date : any){
var _schedule_date = new Date(schedule_date);
var date = new Date();
var transformDate = this.datePipe.transform(date, 'yyyy-MM-dd');
var _today_date = new Date(''+transformDate);
if(_schedule_date < _today_date){
return 'small'
}
else if(_schedule_date > _today_date){
return 'big'
}
else {
return 'same'
}
}
The Best way and recommended way of comparing date in typescript is:
var today = new Date().getTime();
var reqDateVar = new Date(somedate).getTime();
if(today === reqDateVar){
// NOW
} else {
// Some other time
}
TodayDate = new Date();
if (TodayDate > AnotherDate) {} else{}
< = also works, Although with =, it might have to match the milliseconds.
There is a simpler solution
if (inputDate.getDate() === todayDate.getDate()) {
// do stuff
}
like that you don't loose the time attached to inputDate if any

Categories