Using Javascript, how do I make sure a date range is valid? - javascript

In JavaScript, what is the best way to determine if a date provided falls within a valid range?
An example of this might be checking to see if the user input requestedDate is part of the next valid work week. Note that this is not just checking to see if one date is larger than another as a valid date would be equal to or greater than the lower end of the range while less than or equal to the upper end of the range.

This is actually a problem that I have seen come up before a lot in my works and the following bit of code is my answer to the problem.
// checkDateRange - Checks to ensure that the values entered are dates and
// are of a valid range. By this, the dates must be no more than the
// built-in number of days appart.
function checkDateRange(start, end) {
// Parse the entries
var startDate = Date.parse(start);
var endDate = Date.parse(end);
// Make sure they are valid
if (isNaN(startDate)) {
alert("The start date provided is not valid, please enter a valid date.");
return false;
}
if (isNaN(endDate)) {
alert("The end date provided is not valid, please enter a valid date.");
return false;
}
// Check the date range, 86400000 is the number of milliseconds in one day
var difference = (endDate - startDate) / (86400000 * 7);
if (difference < 0) {
alert("The start date must come before the end date.");
return false;
}
if (difference <= 1) {
alert("The range must be at least seven days apart.");
return false;
}
return true;
}
Now a couple things to note about this code, the Date.parse function should work for most input types, but has been known to have issues with some formats such as "YYYY MM DD" so you should test that before using it. However, I seem to recall that most browsers will interpret the date string given to Date.parse based upon the computers region settings.
Also, the multiplier for 86400000 should be whatever the range of days you are looking for is. So if you are looking for dates that are at least one week apart then it should be seven.

So if i understand currenctly, you need to look if one date is bigger than the other.
function ValidRange(date1,date2)
{
return date2.getTime() > date1.getTime();
}
You then need to parse the strings you are getting from the UI, with Date.parse, like this:
ValidRange(Date.parse('10-10-2008'),Date.parse('11-11-2008'));
Does that help?

var myDate = new Date(2008, 9, 16);
// is myDate between Sept 1 and Sept 30?
var startDate = new Date(2008, 9, 1);
var endDate = new Date(2008, 9, 30);
if (startDate < myDate && myDate < endDate) {
alert('yes');
// myDate is between startDate and endDate
}
There are a variety of formats you can pass to the Date() constructor to construct a date. You can also construct a new date with the current time:
var now = new Date();
and set various properties on it:
now.setYear(...);
now.setMonth(...);
// etc
See http://www.javascriptkit.com/jsref/date.shtml or Google for more details.

Related

How to get date difference in JS in days (regardless of hour difference) [duplicate]

What is wrong with the code below?
Maybe it would be simpler to just compare date and not time. I am not sure how to do this either, and I searched, but I couldn't find my exact problem.
BTW, when I display the two dates in an alert, they show as exactly the same.
My code:
window.addEvent('domready', function() {
var now = new Date();
var input = $('datum').getValue();
var dateArray = input.split('/');
var userMonth = parseInt(dateArray[1])-1;
var userDate = new Date();
userDate.setFullYear(dateArray[2], userMonth, dateArray[0], now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds());
if (userDate > now)
{
alert(now + '\n' + userDate);
}
});
Is there a simpler way to compare dates and not including the time?
I'm still learning JavaScript, and the only way that I've found which works for me to compare two dates without the time is to use the setHours method of the Date object and set the hours, minutes, seconds and milliseconds to zero. Then compare the two dates.
For example,
date1 = new Date()
date2 = new Date(2011,8,20)
date2 will be set with hours, minutes, seconds and milliseconds to zero, but date1 will have them set to the time that date1 was created. To get rid of the hours, minutes, seconds and milliseconds on date1 do the following:
date1.setHours(0,0,0,0)
Now you can compare the two dates as DATES only without worrying about time elements.
BEWARE THE TIMEZONE
Using the date object to represent just-a-date straight away gets you into a huge excess precision problem. You need to manage time and timezone to keep them out, and they can sneak back in at any step. The accepted answer to this question falls into the trap.
A javascript date has no notion of timezone. It's a moment in time (ticks since the epoch) with handy (static) functions for translating to and from strings, using by default the "local" timezone of the device, or, if specified, UTC or another timezone. To represent just-a-date™ with a date object, you want your dates to represent UTC midnight at the start of the date in question. This is a common and necessary convention that lets you work with dates regardless of the season or timezone of their creation. So you need to be very vigilant to manage the notion of timezone, both when you create your midnight UTC Date object, and when you serialize it.
Lots of folks are confused by the default behaviour of the console. If you spray a date to the console, the output you see will include your timezone. This is just because the console calls toString() on your date, and toString() gives you a local represenation. The underlying date has no timezone! (So long as the time matches the timezone offset, you still have a midnight UTC date object)
Deserializing (or creating midnight UTC Date objects)
This is the rounding step, with the trick that there are two "right" answers. Most of the time, you will want your date to reflect the local timezone of the user. What's the date here where I am.. Users in NZ and US can click at the same time and usually get different dates. In that case, do this...
// create a date (utc midnight) reflecting the value of myDate and the environment's timezone offset.
new Date(Date.UTC(myDate.getFullYear(),myDate.getMonth(), myDate.getDate()));
Sometimes, international comparability trumps local accuracy. In that case, do this...
// the date in London of a moment in time. Device timezone is ignored.
new Date(Date.UTC(myDate.getUTCFullYear(), myDate.getUTCMonth(), myDate.getUTCDate()));
Deserialize a date
Often dates on the wire will be in the format YYYY-MM-DD. To deserialize them, do this...
var midnightUTCDate = new Date( dateString + 'T00:00:00Z');
Serializing
Having taken care to manage timezone when you create, you now need to be sure to keep timezone out when you convert back to a string representation. So you can safely use...
toISOString()
getUTCxxx()
getTime() //returns a number with no time or timezone.
.toLocaleDateString("fr",{timeZone:"UTC"}) // whatever locale you want, but ALWAYS UTC.
And totally avoid everything else, especially...
getYear(),getMonth(),getDate()
So to answer your question, 7 years too late...
<input type="date" onchange="isInPast(event)">
<script>
var isInPast = function(event){
var userEntered = new Date(event.target.valueAsNumber); // valueAsNumber has no time or timezone!
var now = new Date();
var today = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() ));
if(userEntered.getTime() < today.getTime())
alert("date is past");
else if(userEntered.getTime() == today.getTime())
alert("date is today");
else
alert("date is future");
}
</script>
See it running...
Update 2022... free stuff with tests ...
The code below is now an npm package, Epoq. The code is on github. You're welcome :-)
Update 2019... free stuff...
Given the popularity of this answer, I've put it all in code. The following function returns a wrapped date object, and only exposes those functions that are safe to use with just-a-date™.
Call it with a Date object and it will resolve to JustADate reflecting the timezone of the user. Call it with a string: if the string is an ISO 8601 with timezone specified, we'll just round off the time part. If timezone is not specified, we'll convert it to a date reflecting the local timezone, just as for date objects.
function JustADate(initDate){
var utcMidnightDateObj = null
// if no date supplied, use Now.
if(!initDate)
initDate = new Date();
// if initDate specifies a timezone offset, or is already UTC, just keep the date part, reflecting the date _in that timezone_
if(typeof initDate === "string" && initDate.match(/(-\d\d|(\+|-)\d{2}:\d{2}|Z)$/gm)){
utcMidnightDateObj = new Date( initDate.substring(0,10) + 'T00:00:00Z');
} else {
// if init date is not already a date object, feed it to the date constructor.
if(!(initDate instanceof Date))
initDate = new Date(initDate);
// Vital Step! Strip time part. Create UTC midnight dateObj according to local timezone.
utcMidnightDateObj = new Date(Date.UTC(initDate.getFullYear(),initDate.getMonth(), initDate.getDate()));
}
return {
toISOString:()=>utcMidnightDateObj.toISOString(),
getUTCDate:()=>utcMidnightDateObj.getUTCDate(),
getUTCDay:()=>utcMidnightDateObj.getUTCDay(),
getUTCFullYear:()=>utcMidnightDateObj.getUTCFullYear(),
getUTCMonth:()=>utcMidnightDateObj.getUTCMonth(),
setUTCDate:(arg)=>utcMidnightDateObj.setUTCDate(arg),
setUTCFullYear:(arg)=>utcMidnightDateObj.setUTCFullYear(arg),
setUTCMonth:(arg)=>utcMidnightDateObj.setUTCMonth(arg),
addDays:(days)=>{
utcMidnightDateObj.setUTCDate(utcMidnightDateObj.getUTCDate + days)
},
toString:()=>utcMidnightDateObj.toString(),
toLocaleDateString:(locale,options)=>{
options = options || {};
options.timeZone = "UTC";
locale = locale || "en-EN";
return utcMidnightDateObj.toLocaleDateString(locale,options)
}
}
}
// if initDate already has a timezone, we'll just use the date part directly
console.log(JustADate('1963-11-22T12:30:00-06:00').toLocaleDateString())
// Test case from #prototype's comment
console.log("#prototype's issue fixed... " + JustADate('1963-11-22').toLocaleDateString())
How about this?
Date.prototype.withoutTime = function () {
var d = new Date(this);
d.setHours(0, 0, 0, 0);
return d;
}
It allows you to compare the date part of the date like this without affecting the value of your variable:
var date1 = new Date(2014,1,1);
new Date().withoutTime() > date1.withoutTime(); // true
Using Moment.js
If you have the option of including a third-party library, it's definitely worth taking a look at Moment.js. It makes working with Date and DateTime much, much easier.
For example, seeing if one Date comes after another Date but excluding their times, you would do something like this:
var date1 = new Date(2016,9,20,12,0,0); // October 20, 2016 12:00:00
var date2 = new Date(2016,9,20,12,1,0); // October 20, 2016 12:01:00
// Comparison including time.
moment(date2).isAfter(date1); // => true
// Comparison excluding time.
moment(date2).isAfter(date1, 'day'); // => false
The second parameter you pass into isAfter is the precision to do the comparison and can be any of year, month, week, day, hour, minute or second.
Simply compare using .toDateString like below:
new Date().toDateString();
This will return you date part only and not time or timezone, like this:
"Fri Feb 03 2017"
Hence both date can be compared in this format likewise without time part of it.
Just use toDateString() on both dates. toDateString doesn't include the time, so for 2 times on the same date, the values will be equal, as demonstrated below.
var d1 = new Date(2019,01,01,1,20)
var d2 = new Date(2019,01,01,2,20)
console.log(d1==d2) // false
console.log(d1.toDateString() == d2.toDateString()) // true
Obviously some of the timezone concerns expressed elsewhere on this question are valid, but in many scenarios, those are not relevant.
If you are truly comparing date only with no time component, another solution that may feel wrong but works and avoids all Date() time and timezone headaches is to compare the ISO string date directly using string comparison:
> "2019-04-22" <= "2019-04-23"
true
> "2019-04-22" <= "2019-04-22"
true
> "2019-04-22" <= "2019-04-21"
false
> "2019-04-22" === "2019-04-22"
true
You can get the current date (UTC date, not neccesarily the user's local date) using:
> new Date().toISOString().split("T")[0]
"2019-04-22"
My argument in favor of it is programmer simplicity -- you're much less likely to botch this than trying to handle datetimes and offsets correctly, probably at the cost of speed (I haven't compared performance)
This might be a little cleaner version, also note that you should always use a radix when using parseInt.
window.addEvent('domready', function() {
// Create a Date object set to midnight on today's date
var today = new Date((new Date()).setHours(0, 0, 0, 0)),
input = $('datum').getValue(),
dateArray = input.split('/'),
// Always specify a radix with parseInt(), setting the radix to 10 ensures that
// the number is interpreted as a decimal. It is particularly important with
// dates, if the user had entered '09' for the month and you don't use a
// radix '09' is interpreted as an octal number and parseInt would return 0, not 9!
userMonth = parseInt(dateArray[1], 10) - 1,
// Create a Date object set to midnight on the day the user specified
userDate = new Date(dateArray[2], userMonth, dateArray[0], 0, 0, 0, 0);
// Convert date objects to milliseconds and compare
if(userDate.getTime() > today.getTime())
{
alert(today+'\n'+userDate);
}
});
Checkout the MDC parseInt page for more information about the radix.
JSLint is a great tool for catching things like a missing radix and many other things that can cause obscure and hard to debug errors. It forces you to use better coding standards so you avoid future headaches. I use it on every JavaScript project I code.
An efficient and correct way to compare dates is:
Math.floor(date1.getTime() / 86400000) > Math.floor(date2.getTime() / 86400000);
It ignores the time part, it works for different timezones, and you can compare for equality == too. 86400000 is the number of milliseconds in a day (= 24*60*60*1000).
Beware that the equality operator == should never be used for comparing Date objects because it fails when you would expect an equality test to work because it is comparing two Date objects (and does not compare the two dates) e.g.:
> date1;
outputs: Thu Mar 08 2018 00:00:00 GMT+1300
> date2;
outputs: Thu Mar 08 2018 00:00:00 GMT+1300
> date1 == date2;
outputs: false
> Math.floor(date1.getTime() / 86400000) == Math.floor(date2.getTime() / 86400000);
outputs: true
Notes: If you are comparing Date objects that have the time part set to zero, then you could use date1.getTime() == date2.getTime() but it is hardly worth the optimisation. You can use <, >, <=, or >= when comparing Date objects directly because these operators first convert the Date object by calling .valueOf() before the operator does the comparison.
As I don't see here similar approach, and I'm not enjoying setting h/m/s/ms to 0, as it can cause problems with accurate transition to local time zone with changed date object (I presume so), let me introduce here this, written few moments ago, lil function:
+: Easy to use, makes a basic comparison operations done (comparing day, month and year without time.)
-: It seems that this is a complete opposite of "out of the box" thinking.
function datecompare(date1, sign, date2) {
var day1 = date1.getDate();
var mon1 = date1.getMonth();
var year1 = date1.getFullYear();
var day2 = date2.getDate();
var mon2 = date2.getMonth();
var year2 = date2.getFullYear();
if (sign === '===') {
if (day1 === day2 && mon1 === mon2 && year1 === year2) return true;
else return false;
}
else if (sign === '>') {
if (year1 > year2) return true;
else if (year1 === year2 && mon1 > mon2) return true;
else if (year1 === year2 && mon1 === mon2 && day1 > day2) return true;
else return false;
}
}
Usage:
datecompare(date1, '===', date2) for equality check,
datecompare(date1, '>', date2) for greater check,
!datecompare(date1, '>', date2) for less or equal check
Also, obviously, you can switch date1 and date2 in places to achieve any other simple comparison.
This JS will change the content after the set date
here's the same thing but on w3schools
date1 = new Date()
date2 = new Date(2019,5,2) //the date you are comparing
date1.setHours(0,0,0,0)
var stockcnt = document.getElementById('demo').innerHTML;
if (date1 > date2){
document.getElementById('demo').innerHTML="yes"; //change if date is > set date (date2)
}else{
document.getElementById('demo').innerHTML="hello"; //change if date is < set date (date2)
}
<p id="demo">hello</p> <!--What will be changed-->
<!--if you check back in tomorrow, it will say yes instead of hello... or you could change the date... or change > to <-->
The date.js library is handy for these things. It makes all JS date-related scriping a lot easier.
This is the way I do it:
var myDate = new Date($('input[name=frequency_start]').val()).setHours(0,0,0,0);
var today = new Date().setHours(0,0,0,0);
if(today>myDate){
jAlert('Please Enter a date in the future','Date Start Error', function(){
$('input[name=frequency_start]').focus().select();
});
}
After reading this question quite same time after it is posted I have decided to post another solution, as I didn't find it that quite satisfactory, at least to my needs:
I have used something like this:
var currentDate= new Date().setHours(0,0,0,0);
var startDay = new Date(currentDate - 86400000 * 2);
var finalDay = new Date(currentDate + 86400000 * 2);
In that way I could have used the dates in the format I wanted for processing afterwards. But this was only for my need, but I have decided to post it anyway, maybe it will help someone
This works for me:
export default (chosenDate) => {
const now = new Date();
const today = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
const splitChosenDate = chosenDate.split('/');
today.setHours(0, 0, 0, 0);
const fromDate = today.getTime();
const toDate = new Date(splitChosenDate[2], splitChosenDate[1] - 1, splitChosenDate[0]).getTime();
return toDate < fromDate;
};
In accepted answer, there is timezone issue and in the other time is not 00:00:00
Make sure you construct userDate with a 4 digit year as setFullYear(10, ...) !== setFullYear(2010, ...).
You can use some arithmetic with the total of ms.
var date = new Date(date1);
date.setHours(0, 0, 0, 0);
var diff = date2.getTime() - date.getTime();
return diff >= 0 && diff < 86400000;
I like this because no updates to the original dates are made and perfom faster than string split and compare.
Hope this help!
Comparing with setHours() will be a solution. Sample:
var d1 = new Date();
var d2 = new Date("2019-2-23");
if(d1.setHours(0,0,0,0) == d2.setHours(0,0,0,0)){
console.log(true)
}else{
console.log(false)
}
I know this question have been already answered and this may not be the best way, but in my scenario its working perfectly, so I thought it may help someone like me.
if you have date string as
String dateString="2018-01-01T18:19:12.543";
and you just want to compare the date part with another Date object in JS,
var anotherDate=new Date(); //some date
then you have to convert the string to Date object by using new Date("2018-01-01T18:19:12.543");
and here is the trick :-
var valueDate =new Date(new Date(dateString).toDateString());
return valueDate.valueOf() == anotherDate.valueOf(); //here is the final result
I have used toDateString() of Date object of JS, which returns the Date string only.
Note: Don't forget to use the .valueOf() function while comparing the dates.
more info about .valeOf() is here reference
Happy codding.
This will help. I managed to get it like this.
var currentDate = new Date(new Date().getFullYear(), new Date().getMonth() , new Date().getDate())
var fromdate = new Date(MM/DD/YYYY);
var todate = new Date(MM/DD/YYYY);
if (fromdate > todate){
console.log('False');
}else{
console.log('True');
}
if your date formate is different then use moment.js library to convert the format of your date and then use above code for compare two date
Example :
If your Date is in "DD/MM/YYYY" and wants to convert it into "MM/DD/YYYY" then see the below code example
var newfromdate = new Date(moment(fromdate, "DD/MM/YYYY").format("MM/DD/YYYY"));
console.log(newfromdate);
var newtodate = new Date(moment(todate, "DD/MM/YYYY").format("MM/DD/YYYY"));
console.log(newtodate);
You can use fp_incr(0). Which sets the timezone part to midnight and returns a date object.
Compare Date and Time:
var t1 = new Date(); // say, in ISO String = '2022-01-21T12:30:15.422Z'
var t2 = new Date(); // say, in ISO String = '2022-01-21T12:30:15.328Z'
var t3 = t1;
Compare 2 date objects by milliseconds level:
console.log(t1 === t2); // false - Bcos there is some milliseconds difference
console.log(t1 === t3); // true - Both dates have milliseconds level same values
Compare 2 date objects ONLY by date (Ignore any time difference):
console.log(t1.toISOString().split('T')[0] === t2.toISOString().split('T')[0]);
// true; '2022-01-21' === '2022-01-21'
Compare 2 date objects ONLY by time(ms) (Ignore any date difference):
console.log(t1.toISOString().split('T')[1] === t3.toISOString().split('T')[1]);
// true; '12:30:15.422Z' === '12:30:15.422Z'
Above 2 methods uses toISOString() method so you no need to worry about the time zone difference across the countries.
One option that I ended up using was to use the diff function of Moment.js. By calling something like start.diff(end, 'days') you can compare difference in whole numbers of days.
Works for me:
I needed to compare a date to a local dateRange
let dateToCompare = new Date().toLocaleDateString().split("T")[0])
let compareTime = new Date(dateToCompare).getTime()
let startDate = new Date().toLocaleDateString().split("T")[0])
let startTime = new Date(startDate).getTime()
let endDate = new Date().toLocaleDateString().split("T")[0])
let endTime = new Date(endDate).getTime()
return compareTime >= startTime && compareTime <= endTime
As per usual. Too little, too late.
Nowadays use of momentjs is discouraged (their words, not mine) and dayjs is preferred.
One can use dayjs's isSame.
https://day.js.org/docs/en/query/is-same
dayjs().isSame('2011-01-01', 'date')
There are also a bunch of other units you can use for the comparisons:
https://day.js.org/docs/en/manipulate/start-of#list-of-all-available-units
Using javascript you can set time values to zero for existing date objects and then parse back to Date. After parsing back to Date, Time value is 0 for both and you can do further comparison
let firstDate = new Date(mydate1.setHours(0, 0, 0, 0));
let secondDate = new Date(mydate2.setHours(0, 0, 0, 0));
if (selectedDate == currentDate)
{
console.log('same date');
}
else
{
console.log(`not same date`);
}
Use a library that knows what it's doing
https://day.js.org/docs/en/query/is-same-or-before
dayjs().isSameOrBefore(date, 'day')

javascript / jquery compare datetime values

Seems to be a simple and commonly asked question but after googling for a while havent come up with an answer.
Very simply, I have two variables each with a datetime value in format yyyy-mm-dd hh:mm
I want to compare which is bigger and perform logic accordingly:
example: here
var fromDate = '2014-02-14 07:00';
var toDate = '2014-02-14 07:00';
if (Date.parse(fromDate) > Date.parse(toDate)) {
alert("Invalid Date Range!\nStart Date cannot be after End Date!")
} else {
alert("VALID Date Range!\n Start Date is before End");
}
The above continuously returns the successful validation.
Any advice, suggestions? examples? Thanks,
It happens that the format you're using can be compared lexigraphically. So no parsing required:
var fromDate = '2014-02-14 07:00';
var toDate = '2014-02-14 07:00';
if (fromDate > toDate) {
alert("Invalid Date Range!\nStart Date cannot be after End Date!");
} else {
alert("VALID Date Range!\n Start Date is before End");
}
This is because the most significant fields precede the less significant fields, throughout the string.
But if you really want date/time values, that string format isn't directly supported by the specification. You have three choices:
Use a library like MomentJS.
Massage the string so that it's in a supported format, but be aware that until ES5, there was no standard format dictated by the spec.
Do it yourself
The latter looks something like this:
function parseMyDate(str) {
var parts = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})/.exec(str);
if (!parts) {
return null;
}
return new Date(parseInt(parts[1], 10), // Year
parseInt(parts[2], 10) - 1), // Month
parseInt(parts[3], 10), // Day
parseInt(parts[4], 10), // Hours
parseInt(parts[5], 10)); // Minutes
}
Then use parseMyDate where you have Date.parse above.
this is real ugly but serves the purpose...
var fromDate = '2014-02-27 09:00';
fromDate=fromDate.replace("-", "/");
fromDate=fromDate.replace("-", "/");
var toDate = '2014-02-27 10:00';
toDate=toDate.replace("-", "/");
toDate=toDate.replace("-", "/");
var fromDate=(new Date(fromDate).getTime()/1000);
var toDate=(new Date(toDate).getTime()/1000);
if(fromDate>toDate){
alert('CORRECT');
} else {
alert('INCORRECT, from after to');
}

setDate() set the wrong date on 31st?

This is very weird I don't know what I'm doing wrong. I have a function to grab the date (i.e in this format: 06/24/2011), here's the function:
function checkDate(input){
var d = new Date();
var dspl = input.split("/");
if(dspl.length != 3)
return NaN;
d.setDate(dspl[1]);
d.setMonth(Number(dspl[0])-1);
if(dspl[2].length == 2)
d.setYear("20"+(dspl[2]+""));
else if(dspl[2].length == 4)
d.setYear(dspl[2]);
else
return NaN;
var dt = jsToMsDate(new Date(d));
return dt;
}
If I enter any date of the month, it would parse the date correctly, but if I enter 31st, i.e "01/31/2011", then it would turn into "01/01/2011". I'm not sure what to do and not really sure where the problem might be.
JavaScript's Date objects allow you to give invalid combinations of months and days; they automagically correct those for you (so for instance, if you set the day of the month to 31 when the month is June, it automatically makes it July 1st). That means if you set the fields individually, you can run into situations where that automagic correction gets in your way.
In your case, if you're going to set all three of those fields, you're better off using the form of the Date constructor that accepts them as arguments:
var dt = new Date(year, month, day);
(If you want hours, minutes, seconds, and milliseconds, you can add them as parameters as well.)
So looking at your code, an off-the-cuff update:
function checkDate(input){
var year, month, day, d, dt;
var dspl = input.split("/");
if(dspl.length != 3)
return NaN;
year = parseInt(dspl[2], 10);
month = parseInt(dspl[0], 10) - 1;
day = parseInt(dspl[1], 10);
if (isNaN(year) || isNaN(month) || isNaN(day)) {
return NaN;
}
if (year < 100) {
year += 2000;
}
d = new Date(year, month, day);
var dt = jsToMsDate(d);
return dt;
}
Some other notes on that update:
It's best to use parseInt to parse numbers from end users, and to always specify the radix (10 for decimal). (No, parseInt is not slower than Number or the unary + trick. People assume it is, but it isn't.)
No need to muck about with strings to add 2000 to years given with only two digits. But you can if you like. Note I weakened the validation there, allowing one-digit years for (say) 2001 and three-digit years for (say) 300 AD. So if you need it to be that strong, you'll need to readjust that.
No need to feed the date instance into new Date() again.
You need to set the month before setting the day (or as Marc B points out in his comment, use the Date(yearval, monthval, dayval) constructor).
When you create a Date object, it defaults to the current date. At the time of writing that's in June, so when you try to set the day to 31 it wraps.
...And because of similar behaviour in leap years, you should set the year before setting the month or day.
(It's a good job you developed this code in June rather than in July - the bug would have lurked undiscovered until September, and it would probably have been your users that found it rather than you. :-)
Right hierarchy is set year, then Month and at last add the Day.
This will return the exact date that you added.
function checkDate() {
//Wrong order- will return 1 May 2016
var start = new Date();
start.setDate(31);
start.setMonth(4);
start.setFullYear(2016);
alert(start)
//Right order - will return 31 May 2016
var end = new Date();
end.setFullYear(2016);
end.setMonth(4);
end.setDate(31);
alert(end)
}
<input type="button" value="Test" onclick="checkDate()" />
This is the right heirarchy to set date.
Why are you adding 1 the day position (position 1)? I think that is your problem.
d.setDate(dspl[1] + 1);

Comparing date part only without comparing time in JavaScript

What is wrong with the code below?
Maybe it would be simpler to just compare date and not time. I am not sure how to do this either, and I searched, but I couldn't find my exact problem.
BTW, when I display the two dates in an alert, they show as exactly the same.
My code:
window.addEvent('domready', function() {
var now = new Date();
var input = $('datum').getValue();
var dateArray = input.split('/');
var userMonth = parseInt(dateArray[1])-1;
var userDate = new Date();
userDate.setFullYear(dateArray[2], userMonth, dateArray[0], now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds());
if (userDate > now)
{
alert(now + '\n' + userDate);
}
});
Is there a simpler way to compare dates and not including the time?
I'm still learning JavaScript, and the only way that I've found which works for me to compare two dates without the time is to use the setHours method of the Date object and set the hours, minutes, seconds and milliseconds to zero. Then compare the two dates.
For example,
date1 = new Date()
date2 = new Date(2011,8,20)
date2 will be set with hours, minutes, seconds and milliseconds to zero, but date1 will have them set to the time that date1 was created. To get rid of the hours, minutes, seconds and milliseconds on date1 do the following:
date1.setHours(0,0,0,0)
Now you can compare the two dates as DATES only without worrying about time elements.
BEWARE THE TIMEZONE
Using the date object to represent just-a-date straight away gets you into a huge excess precision problem. You need to manage time and timezone to keep them out, and they can sneak back in at any step. The accepted answer to this question falls into the trap.
A javascript date has no notion of timezone. It's a moment in time (ticks since the epoch) with handy (static) functions for translating to and from strings, using by default the "local" timezone of the device, or, if specified, UTC or another timezone. To represent just-a-date™ with a date object, you want your dates to represent UTC midnight at the start of the date in question. This is a common and necessary convention that lets you work with dates regardless of the season or timezone of their creation. So you need to be very vigilant to manage the notion of timezone, both when you create your midnight UTC Date object, and when you serialize it.
Lots of folks are confused by the default behaviour of the console. If you spray a date to the console, the output you see will include your timezone. This is just because the console calls toString() on your date, and toString() gives you a local represenation. The underlying date has no timezone! (So long as the time matches the timezone offset, you still have a midnight UTC date object)
Deserializing (or creating midnight UTC Date objects)
This is the rounding step, with the trick that there are two "right" answers. Most of the time, you will want your date to reflect the local timezone of the user. What's the date here where I am.. Users in NZ and US can click at the same time and usually get different dates. In that case, do this...
// create a date (utc midnight) reflecting the value of myDate and the environment's timezone offset.
new Date(Date.UTC(myDate.getFullYear(),myDate.getMonth(), myDate.getDate()));
Sometimes, international comparability trumps local accuracy. In that case, do this...
// the date in London of a moment in time. Device timezone is ignored.
new Date(Date.UTC(myDate.getUTCFullYear(), myDate.getUTCMonth(), myDate.getUTCDate()));
Deserialize a date
Often dates on the wire will be in the format YYYY-MM-DD. To deserialize them, do this...
var midnightUTCDate = new Date( dateString + 'T00:00:00Z');
Serializing
Having taken care to manage timezone when you create, you now need to be sure to keep timezone out when you convert back to a string representation. So you can safely use...
toISOString()
getUTCxxx()
getTime() //returns a number with no time or timezone.
.toLocaleDateString("fr",{timeZone:"UTC"}) // whatever locale you want, but ALWAYS UTC.
And totally avoid everything else, especially...
getYear(),getMonth(),getDate()
So to answer your question, 7 years too late...
<input type="date" onchange="isInPast(event)">
<script>
var isInPast = function(event){
var userEntered = new Date(event.target.valueAsNumber); // valueAsNumber has no time or timezone!
var now = new Date();
var today = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() ));
if(userEntered.getTime() < today.getTime())
alert("date is past");
else if(userEntered.getTime() == today.getTime())
alert("date is today");
else
alert("date is future");
}
</script>
See it running...
Update 2022... free stuff with tests ...
The code below is now an npm package, Epoq. The code is on github. You're welcome :-)
Update 2019... free stuff...
Given the popularity of this answer, I've put it all in code. The following function returns a wrapped date object, and only exposes those functions that are safe to use with just-a-date™.
Call it with a Date object and it will resolve to JustADate reflecting the timezone of the user. Call it with a string: if the string is an ISO 8601 with timezone specified, we'll just round off the time part. If timezone is not specified, we'll convert it to a date reflecting the local timezone, just as for date objects.
function JustADate(initDate){
var utcMidnightDateObj = null
// if no date supplied, use Now.
if(!initDate)
initDate = new Date();
// if initDate specifies a timezone offset, or is already UTC, just keep the date part, reflecting the date _in that timezone_
if(typeof initDate === "string" && initDate.match(/(-\d\d|(\+|-)\d{2}:\d{2}|Z)$/gm)){
utcMidnightDateObj = new Date( initDate.substring(0,10) + 'T00:00:00Z');
} else {
// if init date is not already a date object, feed it to the date constructor.
if(!(initDate instanceof Date))
initDate = new Date(initDate);
// Vital Step! Strip time part. Create UTC midnight dateObj according to local timezone.
utcMidnightDateObj = new Date(Date.UTC(initDate.getFullYear(),initDate.getMonth(), initDate.getDate()));
}
return {
toISOString:()=>utcMidnightDateObj.toISOString(),
getUTCDate:()=>utcMidnightDateObj.getUTCDate(),
getUTCDay:()=>utcMidnightDateObj.getUTCDay(),
getUTCFullYear:()=>utcMidnightDateObj.getUTCFullYear(),
getUTCMonth:()=>utcMidnightDateObj.getUTCMonth(),
setUTCDate:(arg)=>utcMidnightDateObj.setUTCDate(arg),
setUTCFullYear:(arg)=>utcMidnightDateObj.setUTCFullYear(arg),
setUTCMonth:(arg)=>utcMidnightDateObj.setUTCMonth(arg),
addDays:(days)=>{
utcMidnightDateObj.setUTCDate(utcMidnightDateObj.getUTCDate + days)
},
toString:()=>utcMidnightDateObj.toString(),
toLocaleDateString:(locale,options)=>{
options = options || {};
options.timeZone = "UTC";
locale = locale || "en-EN";
return utcMidnightDateObj.toLocaleDateString(locale,options)
}
}
}
// if initDate already has a timezone, we'll just use the date part directly
console.log(JustADate('1963-11-22T12:30:00-06:00').toLocaleDateString())
// Test case from #prototype's comment
console.log("#prototype's issue fixed... " + JustADate('1963-11-22').toLocaleDateString())
How about this?
Date.prototype.withoutTime = function () {
var d = new Date(this);
d.setHours(0, 0, 0, 0);
return d;
}
It allows you to compare the date part of the date like this without affecting the value of your variable:
var date1 = new Date(2014,1,1);
new Date().withoutTime() > date1.withoutTime(); // true
Using Moment.js
If you have the option of including a third-party library, it's definitely worth taking a look at Moment.js. It makes working with Date and DateTime much, much easier.
For example, seeing if one Date comes after another Date but excluding their times, you would do something like this:
var date1 = new Date(2016,9,20,12,0,0); // October 20, 2016 12:00:00
var date2 = new Date(2016,9,20,12,1,0); // October 20, 2016 12:01:00
// Comparison including time.
moment(date2).isAfter(date1); // => true
// Comparison excluding time.
moment(date2).isAfter(date1, 'day'); // => false
The second parameter you pass into isAfter is the precision to do the comparison and can be any of year, month, week, day, hour, minute or second.
Simply compare using .toDateString like below:
new Date().toDateString();
This will return you date part only and not time or timezone, like this:
"Fri Feb 03 2017"
Hence both date can be compared in this format likewise without time part of it.
Just use toDateString() on both dates. toDateString doesn't include the time, so for 2 times on the same date, the values will be equal, as demonstrated below.
var d1 = new Date(2019,01,01,1,20)
var d2 = new Date(2019,01,01,2,20)
console.log(d1==d2) // false
console.log(d1.toDateString() == d2.toDateString()) // true
Obviously some of the timezone concerns expressed elsewhere on this question are valid, but in many scenarios, those are not relevant.
If you are truly comparing date only with no time component, another solution that may feel wrong but works and avoids all Date() time and timezone headaches is to compare the ISO string date directly using string comparison:
> "2019-04-22" <= "2019-04-23"
true
> "2019-04-22" <= "2019-04-22"
true
> "2019-04-22" <= "2019-04-21"
false
> "2019-04-22" === "2019-04-22"
true
You can get the current date (UTC date, not neccesarily the user's local date) using:
> new Date().toISOString().split("T")[0]
"2019-04-22"
My argument in favor of it is programmer simplicity -- you're much less likely to botch this than trying to handle datetimes and offsets correctly, probably at the cost of speed (I haven't compared performance)
This might be a little cleaner version, also note that you should always use a radix when using parseInt.
window.addEvent('domready', function() {
// Create a Date object set to midnight on today's date
var today = new Date((new Date()).setHours(0, 0, 0, 0)),
input = $('datum').getValue(),
dateArray = input.split('/'),
// Always specify a radix with parseInt(), setting the radix to 10 ensures that
// the number is interpreted as a decimal. It is particularly important with
// dates, if the user had entered '09' for the month and you don't use a
// radix '09' is interpreted as an octal number and parseInt would return 0, not 9!
userMonth = parseInt(dateArray[1], 10) - 1,
// Create a Date object set to midnight on the day the user specified
userDate = new Date(dateArray[2], userMonth, dateArray[0], 0, 0, 0, 0);
// Convert date objects to milliseconds and compare
if(userDate.getTime() > today.getTime())
{
alert(today+'\n'+userDate);
}
});
Checkout the MDC parseInt page for more information about the radix.
JSLint is a great tool for catching things like a missing radix and many other things that can cause obscure and hard to debug errors. It forces you to use better coding standards so you avoid future headaches. I use it on every JavaScript project I code.
An efficient and correct way to compare dates is:
Math.floor(date1.getTime() / 86400000) > Math.floor(date2.getTime() / 86400000);
It ignores the time part, it works for different timezones, and you can compare for equality == too. 86400000 is the number of milliseconds in a day (= 24*60*60*1000).
Beware that the equality operator == should never be used for comparing Date objects because it fails when you would expect an equality test to work because it is comparing two Date objects (and does not compare the two dates) e.g.:
> date1;
outputs: Thu Mar 08 2018 00:00:00 GMT+1300
> date2;
outputs: Thu Mar 08 2018 00:00:00 GMT+1300
> date1 == date2;
outputs: false
> Math.floor(date1.getTime() / 86400000) == Math.floor(date2.getTime() / 86400000);
outputs: true
Notes: If you are comparing Date objects that have the time part set to zero, then you could use date1.getTime() == date2.getTime() but it is hardly worth the optimisation. You can use <, >, <=, or >= when comparing Date objects directly because these operators first convert the Date object by calling .valueOf() before the operator does the comparison.
As I don't see here similar approach, and I'm not enjoying setting h/m/s/ms to 0, as it can cause problems with accurate transition to local time zone with changed date object (I presume so), let me introduce here this, written few moments ago, lil function:
+: Easy to use, makes a basic comparison operations done (comparing day, month and year without time.)
-: It seems that this is a complete opposite of "out of the box" thinking.
function datecompare(date1, sign, date2) {
var day1 = date1.getDate();
var mon1 = date1.getMonth();
var year1 = date1.getFullYear();
var day2 = date2.getDate();
var mon2 = date2.getMonth();
var year2 = date2.getFullYear();
if (sign === '===') {
if (day1 === day2 && mon1 === mon2 && year1 === year2) return true;
else return false;
}
else if (sign === '>') {
if (year1 > year2) return true;
else if (year1 === year2 && mon1 > mon2) return true;
else if (year1 === year2 && mon1 === mon2 && day1 > day2) return true;
else return false;
}
}
Usage:
datecompare(date1, '===', date2) for equality check,
datecompare(date1, '>', date2) for greater check,
!datecompare(date1, '>', date2) for less or equal check
Also, obviously, you can switch date1 and date2 in places to achieve any other simple comparison.
This JS will change the content after the set date
here's the same thing but on w3schools
date1 = new Date()
date2 = new Date(2019,5,2) //the date you are comparing
date1.setHours(0,0,0,0)
var stockcnt = document.getElementById('demo').innerHTML;
if (date1 > date2){
document.getElementById('demo').innerHTML="yes"; //change if date is > set date (date2)
}else{
document.getElementById('demo').innerHTML="hello"; //change if date is < set date (date2)
}
<p id="demo">hello</p> <!--What will be changed-->
<!--if you check back in tomorrow, it will say yes instead of hello... or you could change the date... or change > to <-->
The date.js library is handy for these things. It makes all JS date-related scriping a lot easier.
This is the way I do it:
var myDate = new Date($('input[name=frequency_start]').val()).setHours(0,0,0,0);
var today = new Date().setHours(0,0,0,0);
if(today>myDate){
jAlert('Please Enter a date in the future','Date Start Error', function(){
$('input[name=frequency_start]').focus().select();
});
}
After reading this question quite same time after it is posted I have decided to post another solution, as I didn't find it that quite satisfactory, at least to my needs:
I have used something like this:
var currentDate= new Date().setHours(0,0,0,0);
var startDay = new Date(currentDate - 86400000 * 2);
var finalDay = new Date(currentDate + 86400000 * 2);
In that way I could have used the dates in the format I wanted for processing afterwards. But this was only for my need, but I have decided to post it anyway, maybe it will help someone
This works for me:
export default (chosenDate) => {
const now = new Date();
const today = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
const splitChosenDate = chosenDate.split('/');
today.setHours(0, 0, 0, 0);
const fromDate = today.getTime();
const toDate = new Date(splitChosenDate[2], splitChosenDate[1] - 1, splitChosenDate[0]).getTime();
return toDate < fromDate;
};
In accepted answer, there is timezone issue and in the other time is not 00:00:00
Make sure you construct userDate with a 4 digit year as setFullYear(10, ...) !== setFullYear(2010, ...).
You can use some arithmetic with the total of ms.
var date = new Date(date1);
date.setHours(0, 0, 0, 0);
var diff = date2.getTime() - date.getTime();
return diff >= 0 && diff < 86400000;
I like this because no updates to the original dates are made and perfom faster than string split and compare.
Hope this help!
Comparing with setHours() will be a solution. Sample:
var d1 = new Date();
var d2 = new Date("2019-2-23");
if(d1.setHours(0,0,0,0) == d2.setHours(0,0,0,0)){
console.log(true)
}else{
console.log(false)
}
I know this question have been already answered and this may not be the best way, but in my scenario its working perfectly, so I thought it may help someone like me.
if you have date string as
String dateString="2018-01-01T18:19:12.543";
and you just want to compare the date part with another Date object in JS,
var anotherDate=new Date(); //some date
then you have to convert the string to Date object by using new Date("2018-01-01T18:19:12.543");
and here is the trick :-
var valueDate =new Date(new Date(dateString).toDateString());
return valueDate.valueOf() == anotherDate.valueOf(); //here is the final result
I have used toDateString() of Date object of JS, which returns the Date string only.
Note: Don't forget to use the .valueOf() function while comparing the dates.
more info about .valeOf() is here reference
Happy codding.
This will help. I managed to get it like this.
var currentDate = new Date(new Date().getFullYear(), new Date().getMonth() , new Date().getDate())
var fromdate = new Date(MM/DD/YYYY);
var todate = new Date(MM/DD/YYYY);
if (fromdate > todate){
console.log('False');
}else{
console.log('True');
}
if your date formate is different then use moment.js library to convert the format of your date and then use above code for compare two date
Example :
If your Date is in "DD/MM/YYYY" and wants to convert it into "MM/DD/YYYY" then see the below code example
var newfromdate = new Date(moment(fromdate, "DD/MM/YYYY").format("MM/DD/YYYY"));
console.log(newfromdate);
var newtodate = new Date(moment(todate, "DD/MM/YYYY").format("MM/DD/YYYY"));
console.log(newtodate);
You can use fp_incr(0). Which sets the timezone part to midnight and returns a date object.
Compare Date and Time:
var t1 = new Date(); // say, in ISO String = '2022-01-21T12:30:15.422Z'
var t2 = new Date(); // say, in ISO String = '2022-01-21T12:30:15.328Z'
var t3 = t1;
Compare 2 date objects by milliseconds level:
console.log(t1 === t2); // false - Bcos there is some milliseconds difference
console.log(t1 === t3); // true - Both dates have milliseconds level same values
Compare 2 date objects ONLY by date (Ignore any time difference):
console.log(t1.toISOString().split('T')[0] === t2.toISOString().split('T')[0]);
// true; '2022-01-21' === '2022-01-21'
Compare 2 date objects ONLY by time(ms) (Ignore any date difference):
console.log(t1.toISOString().split('T')[1] === t3.toISOString().split('T')[1]);
// true; '12:30:15.422Z' === '12:30:15.422Z'
Above 2 methods uses toISOString() method so you no need to worry about the time zone difference across the countries.
One option that I ended up using was to use the diff function of Moment.js. By calling something like start.diff(end, 'days') you can compare difference in whole numbers of days.
Works for me:
I needed to compare a date to a local dateRange
let dateToCompare = new Date().toLocaleDateString().split("T")[0])
let compareTime = new Date(dateToCompare).getTime()
let startDate = new Date().toLocaleDateString().split("T")[0])
let startTime = new Date(startDate).getTime()
let endDate = new Date().toLocaleDateString().split("T")[0])
let endTime = new Date(endDate).getTime()
return compareTime >= startTime && compareTime <= endTime
As per usual. Too little, too late.
Nowadays use of momentjs is discouraged (their words, not mine) and dayjs is preferred.
One can use dayjs's isSame.
https://day.js.org/docs/en/query/is-same
dayjs().isSame('2011-01-01', 'date')
There are also a bunch of other units you can use for the comparisons:
https://day.js.org/docs/en/manipulate/start-of#list-of-all-available-units
Using javascript you can set time values to zero for existing date objects and then parse back to Date. After parsing back to Date, Time value is 0 for both and you can do further comparison
let firstDate = new Date(mydate1.setHours(0, 0, 0, 0));
let secondDate = new Date(mydate2.setHours(0, 0, 0, 0));
if (selectedDate == currentDate)
{
console.log('same date');
}
else
{
console.log(`not same date`);
}
Use a library that knows what it's doing
https://day.js.org/docs/en/query/is-same-or-before
dayjs().isSameOrBefore(date, 'day')

Simple JavaScript not executing?

What could be the cause of the validateDate() function not to execute when called?
The purpose of validateDate() is to take a string like 01/01/2001 and call isValidDate() to determine if the date is valid.
If it's not valid, then a warning message will appear.
function isValidDate(month, day, year){
/*
Purpose: return true if the date is valid, false otherwise
Arguments: day integer representing day of month
month integer representing month of year
year integer representing year
Variables: dteDate - date object
*/
var dteDate;
//set up a Date object based on the day, month and year arguments
//javascript months start at 0 (0-11 instead of 1-12)
dteDate = new Date(year, month, day);
/*
Javascript Dates are a little too forgiving and will change the date to a reasonable guess if it's invalid. We'll use this to our
advantage by creating the date object and then comparing it to the details we put it. If the Date object is different, then it must
have been an invalid date to start with...
*/
return ((day == dteDate.getDate()) && (month == dteDate.getMonth()) && (year == dteDate.getFullYear()));
}
function validateDate(datestring){
month = substr(datestring, 0, 2);
day = substr(datestring, 2, 2);
year = substr(datestring, 6, 4);
if(isValidDate(month, day, year) == false){
alert("Sorry, " + datestring + " is not a valid date.\nPlease correct this.");
return false;
} else {
return true;
}
}
substr is not a function by itself; you must use string.substr(start_index, length).
Since the JavaScript substr method only takes two parameters, not three, this causes execution to halt at the first substr line, and you'll never get output from that function.
I found this by opening Firebug when running your code in a test HTML page. I highly recommend using Firebug for JavaScript debugging.
Try this in your validateDate function, or something similar:
month = datestring.substr(0, 2);
day = datestring.substr(3, 2);
year = datestring.substr(6, 4);
substr is not defined... you need
datestring.substr(0, 2);
you also have a problem with your second substring- it should start at character 3:
day = substr(datestring, 3, 2);
and, month really should be (month - 1) when you create your date
Looking at your code, your date format is "MMDD__YYYY". So your function needs to be as follows:
function isValidDate(month, day, year){
/*
Purpose: return true if the date is valid, false otherwise
Arguments: day integer representing day of month
month integer representing month of year
year integer representing year
Variables: dteDate - date object
*/
var dteDate;
//set up a Date object based on the day, month and year arguments
//javascript months start at 0 (0-11 instead of 1-12)
dteDate = new Date(year, month, day);
alert(d)
/*
Javascript Dates are a little too forgiving and will change the date to a reasonable guess if it's invalid. We'll use this to our
advantage by creating the date object and then comparing it to the details we put it. If the Date object is different, then it must
have been an invalid date to start with...
*/
return ((day == dteDate.getDate()) && (month == dteDate.getMonth()) && (year == dteDate.getFullYear()));
}
function validateDate(datestring){
month = datestring.substring(0, 2);
day = datestring.substring(2, 4);
year = datestring.substring(6, 10);
alert(year)
if(isValidDate(month, day, year) == false){
alert("Sorry, " + datestring + " is not a valid date.\nPlease correct this.");
return false;
} else {
return true;
}
}
validateDate("0202__2010");
If your date is in a more regular format, you can do the following to test if ((new Date("MM/DD/YYYY")) != "Invalid Date")

Categories