Wondering if anyone has a solution for checking if a weekend exist between two dates and its range.
var date1 = 'Apr 10, 2014';
var date2 = 'Apr 14, 2014';
funck isWeekend(date1,date2){
//do function
return isWeekend;
}
Thank you in advance.
EDIT Adding what I've got so far. Check the two days.
function isWeekend(date1,date2){
//do function
if(date1.getDay() == 6 || date1.getDay() == 0){
return isWeekend;
console.log("weekend")
}
if(date2.getDay() == 6 || date2.getDay() == 0){
return isWeekend;
console.log("weekend")
}
}
Easiest would be to just iterate over the dates and return if any of the days are 6 (Saturday) or 0 (Sunday)
Demo: http://jsfiddle.net/abhitalks/xtD5V/1/
Code:
function isWeekend(date1, date2) {
var d1 = new Date(date1),
d2 = new Date(date2),
isWeekend = false;
while (d1 < d2) {
var day = d1.getDay();
isWeekend = (day === 6) || (day === 0);
if (isWeekend) { return true; } // return immediately if weekend found
d1.setDate(d1.getDate() + 1);
}
return false;
}
If you want to check if the whole weekend exists between the two dates, then change the code slightly:
Demo 2: http://jsfiddle.net/abhitalks/xtD5V/2/
Code:
function isFullWeekend(date1, date2) {
var d1 = new Date(date1),
d2 = new Date(date2);
while (d1 < d2) {
var day = d1.getDay();
if ((day === 6) || (day === 0)) {
var nextDate = d1; // if one weekend is found, check the next date
nextDate.setDate(d1.getDate() + 1); // set the next date
var nextDay = nextDate.getDay(); // get the next day
if ((nextDay === 6) || (nextDay === 0)) {
return true; // if next day is also a weekend, return true
}
}
d1.setDate(d1.getDate() + 1);
}
return false;
}
You are only checking if the first or second date is a weekend day.
Loop from the first to the second date, returning true only if one of the days in between falls on a weekend-day:
function isWeekend(date1,date2){
var date1 = new Date(date1), date2 = new Date(date2);
//Your second code snippet implies that you are passing date objects
//to the function, which differs from the first. If it's the second,
//just miss out creating new date objects.
while(date1 < date2){
var dayNo = date1.getDay();
date1.setDate(date1.getDate()+1)
if(!dayNo || dayNo == 6){
return true;
}
}
}
JSFiddle
Here's what I'd suggest to test if a weekend day falls within the range of two dates (which I think is what you were asking):
function containsWeekend(d1, d2)
{
// note: I'm assuming d2 is later than d1 and that both d1 and d2 are actually dates
// you might want to add code to check those conditions
var interval = (d2 - d1) / (1000 * 60 * 60 * 24); // convert to days
if (interval > 5) {
return true; // must contain a weekend day
}
var day1 = d1.getDay();
var day2 = d2.getDay();
return !(day1 > 0 && day2 < 6 && day2 > day1);
}
fiddle
If you need to check if a whole weekend exists within the range, then it's only slightly more complicated.
It doesn't really make sense to pass in two dates, especially when they are 4 days apart. Here is one that only uses one day which makes much more sense IMHO:
var date1 = 'Apr 10, 2014';
function isWeekend(date1){
var aDate1 = new Date(date1);
var dayOfWeek = aDate1.getDay();
return ((dayOfWeek == 0) || (dayOfWeek == 6));
}
I guess this is the one what #MattBurland sugested for doing it without a loop
function isWeekend(start,end){
start = new Date(start);
if (start.getDay() == 0 || start.getDay() == 6) return true;
end = new Date(end);
var day_diff = (end - start) / (1000 * 60 * 60 * 24);
var end_day = start.getDay() + day_diff;
if (end_day > 5) return true;
return false;
}
FIDDLE
Whithout loops, considering "sunday" first day of week (0):
Check the first date day of week, if is weekend day return true.
SUM "day of the week" of the first day of the range and the number of days in the lap.
If sum>5 return true
Use Date.getDay() to tell if it is a weekend.
if(tempDate.getDay()==6 || tempDate.getDay()==0)
Check this working sample:
http://jsfiddle.net/danyu/EKP6H/2/
This will list out all weekends in date span.
Modify it to adapt to requirements.
Good luck.
Related
I'm trying to test to make sure a date is valid in the sense that if someone enters 2/30/2011 then it should be wrong.
How can I do this with any date?
One simple way to validate a date string is to convert to a date object and test that, e.g.
// Expect input as d/m/y
function isValidDate(s) {
var bits = s.split('/');
var d = new Date(bits[2], bits[1] - 1, bits[0]);
return d && (d.getMonth() + 1) == bits[1];
}
['0/10/2017','29/2/2016','01/02'].forEach(function(s) {
console.log(s + ' : ' + isValidDate(s))
})
When testing a Date this way, only the month needs to be tested since if the date is out of range, the month will change. Same if the month is out of range. Any year is valid.
You can also test the bits of the date string:
function isValidDate2(s) {
var bits = s.split('/');
var y = bits[2],
m = bits[1],
d = bits[0];
// Assume not leap year by default (note zero index for Jan)
var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// If evenly divisible by 4 and not evenly divisible by 100,
// or is evenly divisible by 400, then a leap year
if ((!(y % 4) && y % 100) || !(y % 400)) {
daysInMonth[1] = 29;
}
return !(/\D/.test(String(d))) && d > 0 && d <= daysInMonth[--m]
}
['0/10/2017','29/2/2016','01/02'].forEach(function(s) {
console.log(s + ' : ' + isValidDate2(s))
})
Does first function isValidDate(s) proposed by RobG will work for input string '1/2/'?
I think NOT, because the YEAR is not validated ;(
My proposition is to use improved version of this function:
//input in ISO format: yyyy-MM-dd
function DatePicker_IsValidDate(input) {
var bits = input.split('-');
var d = new Date(bits[0], bits[1] - 1, bits[2]);
return d.getFullYear() == bits[0] && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[2]);
}
I recommend to use moment.js. Only providing date to moment will validate it, no need to pass the dateFormat.
var date = moment("2016-10-19");
And then date.isValid() gives desired result.
Se post HERE
This solution does not address obvious date validations such as making sure date parts are integers or that date parts comply with obvious validation checks such as the day being greater than 0 and less than 32. This solution assumes that you already have all three date parts (year, month, day) and that each already passes obvious validations. Given these assumptions this method should work for simply checking if the date exists.
For example February 29, 2009 is not a real date but February 29, 2008 is. When you create a new Date object such as February 29, 2009 look what happens (Remember that months start at zero in JavaScript):
console.log(new Date(2009, 1, 29));
The above line outputs: Sun Mar 01 2009 00:00:00 GMT-0800 (PST)
Notice how the date simply gets rolled to the first day of the next month. Assuming you have the other, obvious validations in place, this information can be used to determine if a date is real with the following function (This function allows for non-zero based months for a more convenient input):
var isActualDate = function (month, day, year) {
var tempDate = new Date(year, --month, day);
return month === tempDate.getMonth();
};
This isn't a complete solution and doesn't take i18n into account but it could be made more robust.
var isDate_ = function(input) {
var status = false;
if (!input || input.length <= 0) {
status = false;
} else {
var result = new Date(input);
if (result == 'Invalid Date') {
status = false;
} else {
status = true;
}
}
return status;
}
this function returns bool value of whether the input given is a valid date or not. ex:
if(isDate_(var_date)) {
// statements if the date is valid
} else {
// statements if not valid
}
I just do a remake of RobG solution
var daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
var isLeap = new Date(theYear,1,29).getDate() == 29;
if (isLeap) {
daysInMonth[1] = 29;
}
return theDay <= daysInMonth[--theMonth]
This is ES6 (with let declaration).
function checkExistingDate(year, month, day){ // year, month and day should be numbers
// months are intended from 1 to 12
let months31 = [1,3,5,7,8,10,12]; // months with 31 days
let months30 = [4,6,9,11]; // months with 30 days
let months28 = [2]; // the only month with 28 days (29 if year isLeap)
let isLeap = ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
let valid = (months31.indexOf(month)!==-1 && day <= 31) || (months30.indexOf(month)!==-1 && day <= 30) || (months28.indexOf(month)!==-1 && day <= 28) || (months28.indexOf(month)!==-1 && day <= 29 && isLeap);
return valid; // it returns true or false
}
In this case I've intended months from 1 to 12. If you prefer or use the 0-11 based model, you can just change the arrays with:
let months31 = [0,2,4,6,7,9,11];
let months30 = [3,5,8,10];
let months28 = [1];
If your date is in form dd/mm/yyyy than you can take off day, month and year function parameters, and do this to retrieve them:
let arrayWithDayMonthYear = myDateInString.split('/');
let year = parseInt(arrayWithDayMonthYear[2]);
let month = parseInt(arrayWithDayMonthYear[1]);
let day = parseInt(arrayWithDayMonthYear[0]);
My function returns true if is a valid date otherwise returns false :D
function isDate (day, month, year){
if(day == 0 ){
return false;
}
switch(month){
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
if(day > 31)
return false;
return true;
case 2:
if (year % 4 == 0)
if(day > 29){
return false;
}
else{
return true;
}
if(day > 28){
return false;
}
return true;
case 4: case 6: case 9: case 11:
if(day > 30){
return false;
}
return true;
default:
return false;
}
}
console.log(isDate(30, 5, 2017));
console.log(isDate(29, 2, 2016));
console.log(isDate(29, 2, 2015));
It's unfortunate that it seems JavaScript has no simple way to validate a date string to these days. This is the simplest way I can think of to parse dates in the format "m/d/yyyy" in modern browsers (that's why it doesn't specify the radix to parseInt, since it should be 10 since ES5):
const dateValidationRegex = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
function isValidDate(strDate) {
if (!dateValidationRegex.test(strDate)) return false;
const [m, d, y] = strDate.split('/').map(n => parseInt(n));
return m === new Date(y, m - 1, d).getMonth() + 1;
}
['10/30/2000abc', '10/30/2000', '1/1/1900', '02/30/2000', '1/1/1/4'].forEach(d => {
console.log(d, isValidDate(d));
});
Hi Please find the answer below.this is done by validating the date newly created
var year=2019;
var month=2;
var date=31;
var d = new Date(year, month - 1, date);
if (d.getFullYear() != year
|| d.getMonth() != (month - 1)
|| d.getDate() != date) {
alert("invalid date");
return false;
}
function isValidDate(year, month, day) {
var d = new Date(year, month - 1, day, 0, 0, 0, 0);
return (!isNaN(d) && (d.getDate() == day && d.getMonth() + 1 == month && d.getYear() == year));
}
I'm trying to test to make sure a date is valid in the sense that if someone enters 2/30/2011 then it should be wrong.
How can I do this with any date?
One simple way to validate a date string is to convert to a date object and test that, e.g.
// Expect input as d/m/y
function isValidDate(s) {
var bits = s.split('/');
var d = new Date(bits[2], bits[1] - 1, bits[0]);
return d && (d.getMonth() + 1) == bits[1];
}
['0/10/2017','29/2/2016','01/02'].forEach(function(s) {
console.log(s + ' : ' + isValidDate(s))
})
When testing a Date this way, only the month needs to be tested since if the date is out of range, the month will change. Same if the month is out of range. Any year is valid.
You can also test the bits of the date string:
function isValidDate2(s) {
var bits = s.split('/');
var y = bits[2],
m = bits[1],
d = bits[0];
// Assume not leap year by default (note zero index for Jan)
var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// If evenly divisible by 4 and not evenly divisible by 100,
// or is evenly divisible by 400, then a leap year
if ((!(y % 4) && y % 100) || !(y % 400)) {
daysInMonth[1] = 29;
}
return !(/\D/.test(String(d))) && d > 0 && d <= daysInMonth[--m]
}
['0/10/2017','29/2/2016','01/02'].forEach(function(s) {
console.log(s + ' : ' + isValidDate2(s))
})
Does first function isValidDate(s) proposed by RobG will work for input string '1/2/'?
I think NOT, because the YEAR is not validated ;(
My proposition is to use improved version of this function:
//input in ISO format: yyyy-MM-dd
function DatePicker_IsValidDate(input) {
var bits = input.split('-');
var d = new Date(bits[0], bits[1] - 1, bits[2]);
return d.getFullYear() == bits[0] && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[2]);
}
I recommend to use moment.js. Only providing date to moment will validate it, no need to pass the dateFormat.
var date = moment("2016-10-19");
And then date.isValid() gives desired result.
Se post HERE
This solution does not address obvious date validations such as making sure date parts are integers or that date parts comply with obvious validation checks such as the day being greater than 0 and less than 32. This solution assumes that you already have all three date parts (year, month, day) and that each already passes obvious validations. Given these assumptions this method should work for simply checking if the date exists.
For example February 29, 2009 is not a real date but February 29, 2008 is. When you create a new Date object such as February 29, 2009 look what happens (Remember that months start at zero in JavaScript):
console.log(new Date(2009, 1, 29));
The above line outputs: Sun Mar 01 2009 00:00:00 GMT-0800 (PST)
Notice how the date simply gets rolled to the first day of the next month. Assuming you have the other, obvious validations in place, this information can be used to determine if a date is real with the following function (This function allows for non-zero based months for a more convenient input):
var isActualDate = function (month, day, year) {
var tempDate = new Date(year, --month, day);
return month === tempDate.getMonth();
};
This isn't a complete solution and doesn't take i18n into account but it could be made more robust.
var isDate_ = function(input) {
var status = false;
if (!input || input.length <= 0) {
status = false;
} else {
var result = new Date(input);
if (result == 'Invalid Date') {
status = false;
} else {
status = true;
}
}
return status;
}
this function returns bool value of whether the input given is a valid date or not. ex:
if(isDate_(var_date)) {
// statements if the date is valid
} else {
// statements if not valid
}
I just do a remake of RobG solution
var daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
var isLeap = new Date(theYear,1,29).getDate() == 29;
if (isLeap) {
daysInMonth[1] = 29;
}
return theDay <= daysInMonth[--theMonth]
This is ES6 (with let declaration).
function checkExistingDate(year, month, day){ // year, month and day should be numbers
// months are intended from 1 to 12
let months31 = [1,3,5,7,8,10,12]; // months with 31 days
let months30 = [4,6,9,11]; // months with 30 days
let months28 = [2]; // the only month with 28 days (29 if year isLeap)
let isLeap = ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
let valid = (months31.indexOf(month)!==-1 && day <= 31) || (months30.indexOf(month)!==-1 && day <= 30) || (months28.indexOf(month)!==-1 && day <= 28) || (months28.indexOf(month)!==-1 && day <= 29 && isLeap);
return valid; // it returns true or false
}
In this case I've intended months from 1 to 12. If you prefer or use the 0-11 based model, you can just change the arrays with:
let months31 = [0,2,4,6,7,9,11];
let months30 = [3,5,8,10];
let months28 = [1];
If your date is in form dd/mm/yyyy than you can take off day, month and year function parameters, and do this to retrieve them:
let arrayWithDayMonthYear = myDateInString.split('/');
let year = parseInt(arrayWithDayMonthYear[2]);
let month = parseInt(arrayWithDayMonthYear[1]);
let day = parseInt(arrayWithDayMonthYear[0]);
My function returns true if is a valid date otherwise returns false :D
function isDate (day, month, year){
if(day == 0 ){
return false;
}
switch(month){
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
if(day > 31)
return false;
return true;
case 2:
if (year % 4 == 0)
if(day > 29){
return false;
}
else{
return true;
}
if(day > 28){
return false;
}
return true;
case 4: case 6: case 9: case 11:
if(day > 30){
return false;
}
return true;
default:
return false;
}
}
console.log(isDate(30, 5, 2017));
console.log(isDate(29, 2, 2016));
console.log(isDate(29, 2, 2015));
It's unfortunate that it seems JavaScript has no simple way to validate a date string to these days. This is the simplest way I can think of to parse dates in the format "m/d/yyyy" in modern browsers (that's why it doesn't specify the radix to parseInt, since it should be 10 since ES5):
const dateValidationRegex = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
function isValidDate(strDate) {
if (!dateValidationRegex.test(strDate)) return false;
const [m, d, y] = strDate.split('/').map(n => parseInt(n));
return m === new Date(y, m - 1, d).getMonth() + 1;
}
['10/30/2000abc', '10/30/2000', '1/1/1900', '02/30/2000', '1/1/1/4'].forEach(d => {
console.log(d, isValidDate(d));
});
Hi Please find the answer below.this is done by validating the date newly created
var year=2019;
var month=2;
var date=31;
var d = new Date(year, month - 1, date);
if (d.getFullYear() != year
|| d.getMonth() != (month - 1)
|| d.getDate() != date) {
alert("invalid date");
return false;
}
function isValidDate(year, month, day) {
var d = new Date(year, month - 1, day, 0, 0, 0, 0);
return (!isNaN(d) && (d.getDate() == day && d.getMonth() + 1 == month && d.getYear() == year));
}
I have requirement to disable tuesday and thursday on this calendar function but it should enable the current date also. Below script will disable past dates and enable only tuesday and thursday but current date is not enabled. i need to enable current date selection and only future tuesday & thursday dates only.
function datefunc(date) {
var today = new Date();
if (date != null) {
var yesterday = new Date();
var futureDate = new Date();
var today = new Date();
today = today.setDate(today.getDate() - 1)
yesterday = yesterday.setDate(yesterday.getDate() - 1);
futureDate = futureDate.setDate(futureDate.getDate() + 1);
if (date < yesterday)
return true;
else if (date == today || date.getDay() != 2 && date.getDay() != 4)
return true;
}
return false;
}
I am going to go ahead and attempt to answer a very ambiguous question. Given that, I am only going to post something that hopefully you can work with.
First off, this date stuff is "hard" so let's leverage StackOverflow to find stuff we can work with (it MIGHT be better to use a date library but let's build from others efforts - up vote them as useful!)
Some additional information on date comparisons: https://stackoverflow.com/a/493018/125981
// credit here: https://stackoverflow.com/a/1353711/125981
function isDate(d) {
if (Object.prototype.toString.call(d) === "[object Date]") {
// it is a date
if (isNaN(d.getTime())) { // d.valueOf() could also work
// date is not valid
return false;
} else {
// date is valid
return true;
}
} else {
// not a date
return false;
}
}
// return true if prior to yesterday, OR is today(exactly), is not tuesday, or is not thursday
function datefunc(date) {
var today = new Date();
if (isDate(date)) {
var yesterday = new Date(new Date().setDate(today.getDate() - 1));
var tomorrow = new Date(new Date().setDate(today.getDate() + 1));
console.log(today.getTime(), yesterday.getTime(), tomorrow.getTime());
if (date.getTime() < yesterday.getTime() || date.getTime() == today.getTime() || (date.getDay() != 2 && date.getDay() != 4)) {
return true;
}
}
return false;
}
// credit here: https://stackoverflow.com/a/27336600/125981
// if d is dow, return that else next dow
function currentOrNexDowDay(d, dow) {
d.setDate(d.getDate() + (dow + (7 - d.getDay())) % 7);
return d;
}
// credit here: https://stackoverflow.com/a/27336600/125981
// if cd is dow and not d, return that else next dow
function nextDowDay(d, dow) {
var cd = new Date(d);
cd.setDate(cd.getDate() + (dow + (7 - cd.getDay())) % 7);
if (d.getTime() === cd.getTime()) {
cd.setDate(cd.getDate() + 7);
}
return cd;
}
// a Tuesday
var checkDate = new Date("2018-02-13T17:30:29.569Z");
console.log(datefunc(checkDate));
// a Wednesday
checkDate = new Date("2018-02-14T17:30:29.569Z");
console.log(datefunc(checkDate));
// a Sunday
checkDate = new Date("2018-02-11T17:30:29.569Z");
console.log(datefunc(checkDate));
// Next Monday
var d = new Date();
d = currentOrNexDowDay(d, 1);
//d.setDate(d.getDate() + (8 - d.getDay()) % 7);
console.log(d);
console.log(datefunc(d));
// Next Tuesday
var dt = new Date();
dt = nextDowDay(dt, 2);
console.log(dt);
console.log(datefunc(dt));
i want to calculate the range between 2 dates without counting weekend in javascript. i have some code that already count the range between them. but i'm stuck with the weekend part. date inputed by CJuiDatePicker in YII framework
<script>
function calcDay(dt1, dt2, range){
var msec1 = dt1;
var date1 = new date(msec1);
var msec2 = dt2;
var date2 = new date(msec2);
if(date1>0 || date2>0){
range.val(isFinite(Math.round(date2-date1)/86400000) || 0);
}
};
</script>
86400000 is day in millisecond
thanks in advance
The function you'll need is getUTCDay().
the pseudo code would be as follows:
1 - determine full weeks (days/7 truncated)
2 - calculate weekday/weekend: 2 * result = weekend days, 5 * result = weekdays.
3 - after that, remainder and starting day of week will determine the 1 or 2 additional days
Hope that helps, let me know if you need the javascript,
- John
Edited, as requested. NOTE: tweaked your original for testing, you should spot the needed changes to restore.
function calcDay(dt1, dt2, range)
{
var msec1 = "October 13, 2014 11:13:00";
var date1 = new Date(msec1);
var msec2 = "October 13, 2013 11:13:00";
var date2 = new Date(msec2);
var days;
var wdays;
var startday;
var nLeft;
// neither should be zero
if(date1>0 && date2>0) {
days = Math.round( Math.abs((date2-date1)/86400000) );
wdays = Math.round(days / 7) * 5;
nLeft = days % 7;
startday = (date1 > date2) ? date2.getUTCDay() : date1.getUTCDay();
if (startday < 2) {
wdays += Math.max(nLeft+startday-1,0);
} else if (startday == 6) {
wdays += Math.max(nLeft-2,0);
} else if (nLeft > (7-startday)) {
wdays += (nLeft-2)
} else {
wdays += Math.min(nLeft, 6-startday)
}
}
};
i found my own solution, but i forgot to share it. this is how i make it
function myUpdate(dt1, dt2,range){
var msec1 = dt1;
var date1 = new Date(msec1);
var msec2 = dt2;
var date2 = new Date(msec2);
var diff = (isFinite(Math.round (date2 - date1) / 86400000) && Math.round (date2 - date1) / 86400000 || 0);
var wEnd=0;
if(date1>0 || date2>0){
for(var i=0; i<=diff; i++){
if(date1.getDay() ==6 || date1.getDay()==0){
wEnd = wEnd + 1;
}
date1.setDate(date1.getDate() + 1);
}
}
range.val(Math.round((diff-wEnd)+1));
};
first u should count the different date, then the date1 will be check if it is sunday or saturday. then date1 will be added 1 till the value of date1 is equal to date2. if date1 is/are saturday or sunday, wEnd will gain 1. so u can substract diff with wEnd. hope this can help u guys
How to check if two dates not on the same day. I came up with this solution but maybe there is a better way to do this:
var actualDate = new Date();
var isNotToday = dateToCheck.getDay() !== actualDate.getDay() || dateToCheck < actualDate - 24 * 60 * 60 * 1000;
Another option is using .toDateString() function to parse both dates into strings. The function formats output to: "Wed Jul 28 1993." Then you can compare both date strings.
actualDate.toDateString() === dateToCheck.toDateString()
// returns true if actualDate is same day as dateToCheck
Here's a Plunker:
http://plnkr.co/edit/J5Dyn78TdDUzX82T0ypA
And more from MDN:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString
How about checking for the same day, month & year:
var isSameDay = (dateToCheck.getDate() == actualDate.getDate()
&& dateToCheck.getMonth() == actualDate.getMonth()
&& dateToCheck.getFullYear() == actualDate.getFullYear())
It would be safest to check day, month and year:
var isNotToday = dateToCheck.getDate() != actualDate.getDate()
|| dateToCheck.getMonth() != actualDate.getMonth()
|| dateToCheck.getFullYear() != actualDate.getFullYear();
This will ensure you don't get oddities when it comes to DST and leap years which could interfere otherwise.
function getStartOfDay(aDate){
//returns the very beginning of the same day
return new Date(aDate.getTime() - aDate.getTime() % 86400000);
}
var aDate1 = getStartOfDay(new Date());
var aDate2 = getStartOfDay(new Date(1981, 7, 3));
var result = aDate1.getTime() === aDate2.getTime();
Don't create the date object with a time so they're both generated at midnight. Then just check the epoch time.
new Date('11/12/2012').getTime() === new Date('11/11/2012').getTime()
> false
new Date('11/12/2012').getTime() === new Date('11/12/2012').getTime()
> true
new Date('November 12, 2012').getTime() === new Date('11/12/2012').getTime()
> true
new Date('12 November, 2012').getTime() === new Date('11/12/2012').getTime()
> true
The dates just need to be parseable by the Date object (I'm on chrome 23.0.1271.17 (Official Build 159779) beta) and if you don't pass a time they'll generate at midnight.
If you're getting a time, just drop it on the floor and test against midnight.
function isEqual(startDate, endDate) {
return endDate.valueOf() == startDate.valueOf();
}
var now =new Date();
var startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var endDate = new Date(2017, 0, 13)
var result = isEqual(startDate , endDate);
console.log(result);
Use a startOf method for instances of Date:
dateA.startOf('day').getTime() === dateB.startOf('day').getTime()
Here's the method:
Date.prototype.startOf = function(unit) {
var clone = new Date(this.getTime()), day;
/* */if (unit === 'second') clone.setMilliseconds(0);
else if (unit === 'minute') clone.setSeconds(0,0);
else if (unit === 'hour' ) clone.setMinutes(0,0,0);
else {
clone.setHours(0,0,0,0);
if (unit === 'week') {
day = clone.getDay();
clone = day ? new Date(clone - 1000 * 60 * 60 * 24 * day) : clone;
}
else if (unit === 'month') clone.setDate(1);
else if (unit === 'year' ) clone.setMonth(0,1);
}
return clone;
};