Difference between 2 dates, should work, but it isn't - javascript

i have got the following code which should simply tell me difference between 2 months, however all that it is returning is 1 and I can't figure it out!
function parseDate(str) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(str);
return d;
}
Array.prototype.monthDifference = function() {
var months = this[1].getMonth() - this[0].getMonth() + (12 * (this[1].getFullYear() - this[0].getFullYear()));
if(this[1].getDate() < this[0].getDate()){
months--;
}
return months;
};
console.log([parseDate('01/01/2017'), parseDate('02/04/2017')].monthDifference());
Edit
Okay, see updated code below:
Array.prototype.monthDifference = function() {
console.log((this[1].getMonth()+1) - (this[0].getMonth()+1));
var months = (this[1].getMonth()+1) - (this[0].getMonth()+1) + (12 * (this[1].getFullYear() - this[0].getFullYear()));
if(this[1].getDate() < this[0].getDate()){
months--;
}
return (months > 1) ? 0 : months;
};
[pubDate, new Date()].monthDifference();
And now the output, how is one of the numbers negative and the other positive!? And comparing against today and dates in the past...
1
Sat Apr 27 1907 00:00:00 GMT+0100 (BST) Wed May 28 1902 00:00:00 GMT+0100 (BST)
-10
Wed Mar 26 1930 00:00:00 GMT+0000 (GMT) Wed May 28 1902 00:00:00 GMT+0100 (BST)
-10
Tue Mar 26 1929 00:00:00 GMT+0000 (GMT) Wed May 28 1902 00:00:00 GMT+0100 (BST)
-10
Tue Mar 26 1929 00:00:00 GMT+0000 (GMT) Wed May 28 1902 00:00:00 GMT+0100 (BST)
-1
Tue Jun 24 1913 00:00:00 GMT+0100 (BST) Wed May 28 1902 00:00:00 GMT+0100 (BST)

What about this ?
It gives days between two date.
Array.prototype.monthDifference = function() {
var b = this[0].getTime();
var x = this[1].getTime();
var y = x-b;
return Math.floor(y / (24*60*60*1000));
};
var a = [];
a.push(parseDate('01/01/2016'));
a.push(parseDate('02/04/2017'));
console.log(a.monthDifference());

The JavaScript Date constructor doesn't parse strings in UK format(dd/mm/yyyy).
You can split the date string and and then pass it into Date constructor.
Working fiddle: Date foramte fiddle
function formateDateToUK(dateString){
var splitDate = dateString.split('/'),
day = splitDate[0],
month = splitDate[1] - 1, //Javascript months are 0-11
year = splitDate[2],
formatedDate = new Date(year, month, day);
return formatedDate;
}

you functions returns '1', since it is the correct result :)
try:
console.log([parseDate('01/01/2017'), parseDate('07/01/2017')].monthDifference());
and it returns '6'... which is correct.
Note: 'new Date(str)' expects "MM/dd/yyyy" not "dd/MM/yyyy".
Hope this helps

Related

Google Apps Script add month to a date until specific date is reached

I have the following code using Google Apps Script, but when I log it out I get the following results. I want GAS to log the next month and stop once it gets to "lastDateofYear ". For whatever reason, the year doesn't change in my results, it just keeps repeating the current year. Please help.
var thisDate = "Mon Dec 20 00:00:00 GMT-06:00 2021";
var nextYear = Number(currentYear)+1;
var lastDateofYear = new Date("12-31-"+nextYear);
for(var i=thisDate; i <= lastDateofYear; ){
var currentiDate = new Date(i);
var month = currentiDate.getMonth()+1;
i.setMonth((month) % 12);
i.setDate(currentiDate.getDate());
Logger.log(currentiDate);
}
RESULTS:
Mon Dec 20 00:00:00 GMT-06:00 2021
Wed Jan 20 00:00:00 GMT-06:00 2021
Sat Feb 20 00:00:00 GMT-06:00 2021
Sat Mar 20 00:00:00 GMT-05:00 2021
Tue Apr 20 00:00:00 GMT-05:00 2021
Thu May 20 00:00:00 GMT-05:00 2021
Sun Jun 20 00:00:00 GMT-05:00 2021
Tue Jul 20 00:00:00 GMT-05:00 2021
Fri Aug 20 00:00:00 GMT-05:00 2021
Mon Sep 20 00:00:00 GMT-05:00 2021
Wed Oct 20 00:00:00 GMT-05:00 2021
Sat Nov 20 00:00:00 GMT-06:00 2021
Mon Dec 20 00:00:00 GMT-06:00 2021
Wed Jan 20 00:00:00 GMT-06:00 2021
Sat Feb 20 00:00:00 GMT-06:00 2021
Sat Mar 20 00:00:00 GMT-05:00 2021
Tue Apr 20 00:00:00 GMT-05:00 2021
As I understand it, you want to print each month from the given date to the last month of the next year of the given date in the log.
You can do this in the following code:
let start = new Date("Mon Dec 20 00:00:00 GMT-06:00 2021");
let currentYear = new Date().getFullYear();
let nextYear = currentYear + 1;
let end = new Date(nextYear, 11, 31);
while (start <= end) {
// You can use Logger.log() here if you want. I use console.log() for demo purpose
console.log(new Date(start).toDateString());
start.setMonth(start.getMonth() + 1);
}
If I got any part wrong, feel free to point it out to me in the comments.
There is a lot to say about your code:
var thisDate = "Mon Dec 20 00:00:00 GMT-06:00 2021";
That timestamp format is not supported by ECMA-262, so don't use the built–in parser to parse it, see Why does Date.parse give incorrect results?
var nextYear = Number(currentYear)+1;
Where does currentYear come from?
var lastDateofYear = new Date("12-31-"+nextYear);
Parsing of an unsupported format, see above. In Safari it returns an invalid date.
for(var i=thisDate; i <= lastDateofYear; ){
Sets i to the string value assigned to thisDate. Since lastDateOfYear is an invalid date in Safari and Firefox, so the test i <= NaN is never true and the loop is never entered.
var currentiDate = new Date(i);
Parses i, see above.
var month = currentiDate.getMonth()+1;
i.setMonth((month) % 12);
i is a string, which doesn't have a setMonth method so I'd expect a Type error like "i.setMonth is not a function" if the loop actually runs.
i.setDate(currentiDate.getDate());
Another Type error as above (but it won't get this far).
Logger.log(currentiDate);
}
It seems you want to sequentially add 1 month to a date until it reaches the same date in the following year. Trivially, you can just add 1 month until you get to the same date next year, something like:
let today = new Date();
let nextYear = new Date(today.getFullYear() + 1, today.getMonth(), today.getDate());
let result = [];
do {
result.push(today.toString());
today.setMonth(today.getMonth() + 1);
} while (today <= nextYear)
However, adding months is not that simple. If you add 1 month to 1 Jan, you'll get 2 or 3 Mar depending on whether it's a leap year or not. And adding 1 month to 31 Aug will return 1 Oct.
Many "add month" functions check to see if the date rolls over an extra month and if it does, set the date back to the end of the previous month by setting the date to 0, so 31 Jan + 1 month gives 28 or 29 Feb.
But if you cycle over a year using that algorithm, you'll get say 31 Jan, 28 Feb, 28 Mar, 28 Apr etc. rather than 31 Jan, 28 Feb, 31 Mar, 30 Apr, etc.
See JavaScript function to add X months to a date and How to add months to a date in JavaScript?
A more robust way is to have a function that adds n months to a date and increment the months to add rather than the date itself so the month–end problem can be dealt with separately for each addition, e.g.
/* Add n months to a date. If date rolls over an extra month,
* set to last day of previous month, e.g.
* 31 Jan + 1 month => 2 Mar, roll back => 28 Feb
*
* #param {number} n - months to add
* #param {Date} date - date to add months to, default today
* #returns {Date} new Date object, doesn't modify passed Date
*/
function addMonths(n, date = new Date()) {
let d = new Date(+date);
let day = d.getDate();
d.setMonth(d.getMonth() + n);
if (d.getDate() != day) d.setDate(0);
return d;
}
/* return array of n dates at 1 month intervals. List is
* inclusive so n + 1 Dates returned.
*
* #param {Date} start - start date
* #param {number} n - number of months to return
* #returns {Array} array of Dates
*/
function getMonthArray(n, start = new Date()) {
let result = [];
for (let i=0; i<n; i++) {
result.push(addMonths(i, start));
}
return result;
}
// Examples
// Start on 1 Dec
getMonthArray(12, new Date(2021,11,1)).forEach(
d => console.log(d.toDateString())
);
// Start on 31 Dec
getMonthArray(12, new Date(2021,11,31)).forEach(
d => console.log(d.toDateString())
);
The functions don't attempt to parse timestamps to Dates, that responsibility is left to the caller.

How to increase the date when moving to the other month

I have a date set which I am filling it with the number of current week and year:
dateSets(week, year) {
let fistDayOfTheWeek = '';
if(this.currentWeekNumber === this.getWeekNumber(new Date())) {
fistDayOfTheWeek = new Date();
} else {
fistDayOfTheWeek = this.getDateOfWeek(week, year);
}
let sunday = new Date(fistDayOfTheWeek);
sunday.setDate(sunday.getDate() - sunday.getDay() + 7);
const dates = [];
const diff = sunday.getDate() - fistDayOfTheWeek.getDate();
for (let i = 0; i <= diff; i++) {
const upDate = new Date();
upDate.setDate(fistDayOfTheWeek.getDate() + i);
dates.push(upDate);
}
console.log(dates)
return dates;
},
So apperantly my dateSet function works like if it is not monday then show the dates from today to sunday and from next week from monday to sunday. But what is wrong in this function is it doesnt push when the month is changed. So for 4 weeks console.log(dates) displays:
[Tue Aug 10 2021 16:22:43 GMT+0200 (Central European Summer Time),
Wed Aug 11 2021 16:22:43 GMT+0200 (Central European Summer Time), Thu
Aug 12 2021 16:22:43 GMT+0200 (Central European Summer Time), Fri Aug
13 2021 16:22:43 GMT+0200 (Central European Summer Time), Sat Aug 14
2021 16:22:43 GMT+0200 (Central European Summer Time), Sun Aug 15
2021 16:22:43 GMT+0200 (Central European Summer Time)]
[Mon Aug 16 2021 16:22:46 GMT+0200 (Central European Summer Time),
Tue Aug 17 2021 16:22:46 GMT+0200 (Central European Summer Time), Wed
Aug 18 2021 16:22:46 GMT+0200 (Central European Summer Time), Thu Aug
19 2021 16:22:46 GMT+0200 (Central European Summer Time), Fri Aug 20
2021 16:22:46 GMT+0200 (Central European Summer Time), Sat Aug 21
2021 16:22:46 GMT+0200 (Central European Summer Time), Sun Aug 22
2021 16:22:46 GMT+0200 (Central European Summer Time)]
[Mon Aug 23 2021 16:22:47 GMT+0200 (Central European Summer Time),
Tue Aug 24 2021 16:22:47 GMT+0200 (Central European Summer Time), Wed
Aug 25 2021 16:22:47 GMT+0200 (Central European Summer Time), Thu Aug
26 2021 16:22:47 GMT+0200 (Central European Summer Time), Fri Aug 27
2021 16:22:47 GMT+0200 (Central European Summer Time), Sat Aug 28
2021 16:22:47 GMT+0200 (Central European Summer Time), Sun Aug 29
2021 16:22:47 GMT+0200 (Central European Summer Time)]
[]
As you see since after 3 weeks, the month will be changed to september and I think that's why it comes to an empty array.
I dont know if it is necessary but in any case here are the other functions that I used:
getDateOfWeek(w, y) {
var simple = new Date(y, 0, 1 + (w - 1) * 7);
var dow = simple.getDay();
var ISOweekStart = simple;
if (dow <= 4)
ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);
else
ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());
return ISOweekStart;
}
getWeekNumber(date) {
const temp_date = new Date(date.valueOf());
const dayn = (date.getDay() + 6) % 7;
temp_date.setDate(temp_date.getDate() - dayn + 3);
const firstThursday = temp_date.valueOf();
temp_date.setMonth(0, 1);
if (temp_date.getDay() !== 4)
{
temp_date.setMonth(0, 1 + ((4 - temp_date.getDay()) + 7) % 7);
}
return 1 + Math.ceil((firstThursday - temp_date) / 604800000);
},
PS: currentWeekNumber is increasing everytime when the button is clicked.
Your issue is here:
const diff = sunday.getDate() - fistDayOfTheWeek.getDate();
when you get to the end of the month of say August, the next Sunday is 5 Sep and the first day of the week is 30 August, so diff is -25 and in the test:
for (let i = 0; i <= diff; i++) {
i is less than diff from the start so nothing is added to the array.
One fix is to get the number of days until the next Sunday and iterate for that many days, e.g.
// Return an array of dates from tomorrow until the
// following Sunday.
function getDatesToSunday(date = new Date()) {
// Copy date so don't affect original
let d = new Date(+date);
// Get the number of days until the next Sunday
let count = 7 - d.getDay();
// Create array of Dates
let dates = [];
while (count--) { 
dates.push (new Date(d.setDate(d.getDate() + 1)));
}
return dates;
}
console.log('Given Sun 29 Aug 2021:');
getDatesToSunday(new Date(2021, 7, 29))
.forEach(d => console.log(d.toDateString()));
console.log('Rest of this week, or next if today is Sunday:');
getDatesToSunday()
.forEach(d => console.log(d.toDateString()));
If the supplied date is Saturday, the above returns an array of just Sunday. If the supplied date is Sunday, it returns an array of the following Monday to Sunday, etc.
If you want to get multiple weeks of dates, add a second parameter, say weeks that defaults to 1, then add (weeks - 1) * 7 to count before the while loop. Test weeks first to ensure it's 1 or greater (starting a decrementing while loop with a negative number is not a good idea).
Or you can just keep adding days until Sunday:
const getDatesToSunday = (date = new Date()) => {
// Setup
let year = date.getFullYear(),
month = date.getMonth(),
day = date.getDate(),
dates = [];
// Add dates from tomorrow until Sunday
do {
dates.push(new Date(year, month, ++day));
} while (dates[dates.length - 1].getDay());
return dates;
};
getDatesToSunday().forEach(d=>console.log(d.toDateString()));

How do I find the nearest Past or Future Date in an array of Dates by an DateObject?

Let's say we have an Array of Dates
var dateArr = [new Date("Thu Apr 01 2021 00:00:00 GMT+0200"), new Date("Sat May 01 2021 00:00:00 GMT+0200")];
and an Date Object, which we need to search in the dateArr, for example:
var findDate = new Date("Mon Apr 05 2021 07:50:06 GMT+0200");
And all together we have this PLUS
a function to return us the nearestDate in
dateArr by findDate which can lie in the past or future
var dateArr = [new Date("Thu Apr 01 2021 00:00:00 GMT+0200"), new Date("Sat May 01 2021 00:00:00 GMT+0200")];
var findDate = new Date("Mon Apr 05 2021 07:50:06 GMT+0200");
var result = getNearestDateInDateArrByFindDate(dateArr, findDate);
console.log(result); //should print to console: Thu Apr 01 2021 00:00:00 GMT+0200
function getNearestDateInDateArrByFindDate(dateArr, findDate) {
var nearestDateInPastOrFuture;
...
return nearestDateInPastOrFuture;
}
What I tried so far without sucess ...
var dateArr = [new Date("Thu Apr 01 2021 00:00:00 GMT+0200"), new Date("Sat May 01 2021 00:00:00 GMT+0200")];
var findDate = new Date("Mon Apr 05 2021 07:50:06 GMT+0200");
function getNearestDateInDateArrByFindDate(dateArr, findDate) {
console.log(dateArr);
console.log(findDate);
var nearestFutureDates = dateArr.filter(dt => dt.getTime() >= findDate.getTime());
var nearestFutureDates = nearestFutureDates.sort((a, b) => a.getTime() - b.getTime());
var nearestPastOrFutureDate = dateArr.filter(dt => dt.getTime() >= findDate.getTime());
var nearestPastOrFutureDate = nearestPastOrFutureDate.sort((a, b) => (findDate.getTime() - a.getTime()) - (findDate.getTime() - b.getTime()));
console.log(nearestFutureDates);
console.log(nearestPastOrFutureDate);
//returns always sat May 01 2021 00:00:00 GMT+0200
}
getNearestDateInDateArrByFindDate(dateArr, findDate)
And somehow the snippet doesn't return Apr 01 but rather April 31?
We can use Array.sort() to sort by the difference in ms from each date to findDate.
NB: We can get the absolute difference in milliseconds between two dates using
Math.abs(date1 - date2);
So we'll use this to sort like so:
var dateArr = [new Date("Thu Apr 01 2021 00:00:00 GMT+0200"), new Date("Sat May 01 2021 00:00:00 GMT+0200")];
var findDate = new Date("Mon Apr 05 2021 07:50:06 GMT+0200");
var result = getNearestDateInDateArrByFindDate(dateArr, findDate);
console.log(result); //should print to console: Thu Apr 01 2021 00:00:00 GMT+0200
function getNearestDateInDateArrByFindDate(dateArr, findDate) {
const sortedByDiff = [...dateArr].sort((a,b) => {
// Sort by the absolute difference in ms between dates.
return Math.abs(a - findDate) - Math.abs(b - findDate);
})
// Return the first date (the one with the smallest difference)
return sortedByDiff[0];
}
You can filter what is the nearest date on past and the nearest on future.
Optionally you can apply .sort((a, b) => a - b) to your array of dates if are not ordered.
const dateArr = [new Date("Thu Apr 01 2021 00:00:00 GMT+0200"), new Date("Sat May 01 2021 00:00:00 GMT+0200")].sort((a, b) => a - b);
const findDate = new Date("Mon Apr 05 2021 07:50:06 GMT+0200");
const nearestPastDate = (dateArr, date) => {
const pastArr = dateArr.filter(n => n <= date);
return pastArr.length > 0 ? pastArr[pastArr.length-1]: null;
};
const nearestFutureDate = (dateArr, date) => {
const futArr = dateArr.filter(n => n >= date);
return futArr.length > 0 ? futArr[0]: null;
};
console.log(dateArr);
console.log(nearestPastDate(dateArr, findDate));
console.log(nearestFutureDate(dateArr, findDate));

How correctly check if 2 date (having different time) are in the same day (day, month, yeah) using JavaScript?

I am not so into JavaScript and I have to check if 2 date have the same day\month\year (not the time, so only if the day is the same). I have to use only old plain JavaScript
I have 2 Date variable and I was trying to do in this way:
if(previousDate.getDate() === dateCurrentForecast.getDate()) {
console.log("SAME DATE");
}
Where:
previousDate = Sun Nov 05 2017 06:00:00 GMT+0100 (ora solare Europa occidentale)
dateCurrentForecast = Sun Nov 05 2017 12:00:00 GMT+0100 (ora solare Europa occidentale)
I have to find a way to check that these 2 date are in the same day (Sun Nov 05 2017).
Using the previous snipet it seems to work because both previousDate.getDate() and dateCurrentForecast.getDate() returns the value 5, but what exactly means this returned value?
What is the correct way to do this kind of check?
You can remove timestamp part of date and then compare the value:
Note: Remember to create new objects else you will mutate original objects.
function isSameDay(d1, d2) {
var _d1 = new Date(+d1);
var _d2 = new Date(+d2);
_d1.setHours(0,0,0,0)
_d2.setHours(0,0,0,0)
return +_d1 === +_d2;
}
var d1 = new Date('Sun Nov 05 2017 06:00:00 GMT+0100 (ora solare Europa occidentale)');
var d2 = new Date('Sun Nov 05 2017 12:00:00 GMT+0100 (ora solare Europa occidentale)')
console.log(isSameDay(d1, d2))
or you can check for values manually:
function isSameDay(d1, d2) {
return d1.getDate() === d2.getDate() &&
d2.getMonth() === d2.getMonth() &&
d1.getFullYear === d2.getFullYear();
}
var d1 = new Date('Sun Nov 05 2017 06:00:00 GMT+0100 (ora solare Europa occidentale)');
var d2 = new Date('Sun Nov 05 2017 12:00:00 GMT+0100 (ora solare Europa occidentale)')
console.log(isSameDay(d1, d2))
JavaScript Date object methods are sometimes unobvious because getDate method returns day of the month and not a date string as it might be expected from method name.
You can accomplish your task by creating copy of your date objects and comparing them. It may be good idea to use UTC versions of methods to avoid cross-timezone differences:
function isSameDay(d1, d2) {
var date1 = new Date(Date.UTC(d1.getYear(), d1.getMonth(), d1.getDay()));
var date2 = new Date(Date.UTC(d2.getYear(), d2.getMonth(), d2.getDay()));
return date1.getTime() === date2.getTime();
}
console.log(isSameDay(
new Date('Sun Nov 05 2017 06:00:00 GMT+0100'),
new Date('Sun Nov 05 2017 12:00:00 GMT+0100')
));
console.log(isSameDay(
new Date('Sun Nov 06 2017 06:00:00 GMT+0100'),
new Date('Sun Nov 05 2017 12:00:00 GMT+0100')
));
Your actual code will work even if the two dates have different months or years when they have the same day.
You need to check upon year, month and day:
function areThe2DatesEqualByDay(d1, d2) {
if (d1.getYear() === d2.getYear()) {
if (d1.getMonth() === d2.getMonth()) {
if (d1.getDate() === d2.getDate())
return true;
}
}
return false;
}
Demo:
var previousDate = "Sun Nov 05 2017 06:00:00 GMT+0100";
var dateCurrentForecast = "Sun Nov 05 2017 12:00:00 GMT+0100";
var diffDate = "Sun Mar 05 2017 12:00:00 GMT+0100";
function areThe2DatesEqualByDay(d1, d2) {
if (d1.getYear() === d2.getYear()) {
if (d1.getMonth() === d2.getMonth()) {
if (d1.getDate() === d2.getDate())
return true;
}
}
return false;
}
console.log(areThe2DatesEqualByDay(new Date(), new Date()));
console.log(areThe2DatesEqualByDay(new Date(previousDate), new Date(dateCurrentForecast)));
console.log(areThe2DatesEqualByDay(new Date(previousDate), new Date(diffDate)));
getDate returns the day of the month. So you are now only checking if the day of the month is the samen. With getMonth and getYear you could check the month and the year of both dates.
if (previousDate.getDate() === dateCurrentForecast.getDate() && previousDate.getMonth() === dateCurrentForecast.getMonth() && previousDate.getYear() === dateCurrentForecast.getYear()) { console.log('the same'); }
The getDate function returns the day of the month, that the Date object represents. So to check if two Date objects represents the say day, while ignoring the time of day, you need to compare the day of month, the month, and the year.
var d1 = new Date("Sun Nov 05 2017 06:00:00 GMT+0100");
var d2 = new Date("Sun Nov 05 2017 12:00:00 GMT+0100");
var sameDate = d1.getDate() === d2.getDate() && d1.getMonth() === d2.getMonth() && d1.getYear() == d2.getYear();
console.log("Are they the same date?", sameDate);

How to check if two arrays of dates have matching items?

I have two arrays of dates. The first one have all the booked dates and the second one will have dates between "start day" and "end day" which user will pick.
Now I have to confirm that the days between the start and stop will not be found from the fully booked dates array.
I'm using Vue.js to update data.
Here is what I have done to get those dates:
/**
* Get dates from datepicker and format it to the same format that fully booked array has it's dates.
**/
var day1 = moment( this.startDate, 'DD/MM/Y').format('Y,M,D');
var day2 = moment( this.endDate, 'DD/MM/Y').format('Y,M,D');
var start = new Date(day1);
var end = new Date(day2);
/**
* Get dates between start and stop and return them in the dateArray.
**/
Date.prototype.addDays = function(days) {
var dat = new Date(this.valueOf());
dat.setDate(dat.getDate() + days);
return dat;
};
function getDates(startDate, stopDate) {
var dateArray = [];
var currentDate = startDate;
while (currentDate <= stopDate) {
dateArray.push(currentDate);
currentDate = currentDate.addDays(1);
}
return dateArray;
}
var dateArray = getDates(start, end);
/**
* Set dateArray in to Vue.js data.
**/
this.$set('daysBetweenStartStop', dateArray);
/**
* Get arrays of dates from the Vue.js data. calendar = Booked dates | matchingDays = Dates between start and stop.
**/
var calendar = this.fullDates;
var matchingDays = this.daysBetweenStartStop;
/**
* #description determine if an array contains one or more items from another array.
* #param {array} haystack the array to search.
* #param {array} arr the array providing items to check for in the haystack.
* #return {boolean} true|false if haystack contains at least one item from arr.
*/
var findIfMatch = function (haystack, arr) {
return arr.some(function (v) {
return haystack.indexOf(v) >= 0;
});
};
var matching = findIfMatch(calendar, matchingDays);
/**
* Check the results. If false we are good to go.
**/
if (matching){
alert('WE FOUND A MATCH');
} else {
alert('GOOD TO GO');
}
Arrays are in the following format:
var calendar = [
Sun Oct 02 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 09 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 16 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 23 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 30 2016 00:00:00 GMT+0300 (EEST)
]
var matchingDays = [
Fri Oct 28 2016 00:00:00 GMT+0300 (EEST),
Sat Oct 29 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 30 2016 00:00:00 GMT+0300 (EEST)
]
My problem is that even if those two arrays have exactly same dates they will still somehow be considered as a not identical. Any ideas how to get this working?
Your match function should look like this :
findIfMatch = function (haystack, arr){
var i = 0;//array index
var j = 0;//array index
while(j < arr.length && i < haystack.length){
cur_cal = Date.parse(haystack[i]);
cur_match = Date.parse(arr[j]);
if(cur_cal > cur_match){
j++;
}else if(cur_cal < cur_match){
i++;
}else{
return true;
}
}
return false;
}
To get matching records from two array use this
var calendar = [
Sun Oct 02 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 09 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 16 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 23 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 30 2016 00:00:00 GMT+0300 (EEST)
];
var matchingDays = [
Fri Oct 28 2016 00:00:00 GMT+0300 (EEST),
Sat Oct 29 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 30 2016 00:00:00 GMT+0300 (EEST)
];
var newCalendar = [];
var newMatchingDays = []
$.map(calendar, function(date){
newCalendar.push(date.toString())
});
$.map(matchingDays, function(date){
newMatchingDays.push(date.toString())
});
var result = [];
$.map(newCalendar, function (val, i) {
if ($.inArray(val, newMatchingDays) > -1) {
result.push(val);
}
});
console.log(result);
Firstly you can't compare dates like that, Date is an object.
eg.
var d1 = new Date('2016-09-30');
var d1 = new Date('2016-09-30');
console.log(d1 === d2); // = false
You would need to loop the array and compare each item, rather than use indexOf.
or maybe use the Array.filter(). Or alternatively use and object as a lookup.
eg. If say you had ->
var calendar = {
"Sun Oct 02 2016 00:00:00 GMT+0300 (EEST)": true,
"Sun Oct 09 2016 00:00:00 GMT+0300 (EEST)": true,
"Sun Oct 16 2016 00:00:00 GMT+0300 (EEST)": true,
"Sun Oct 23 2016 00:00:00 GMT+0300 (EEST)": true,
"Sun Oct 30 2016 00:00:00 GMT+0300 (EEST)": true
};
if (calendar["Sun Oct 16 2016 00:00:00 GMT+0300 (EEST)"]) {
console.log("We have date");
}
Notice how I use a string representation for the date, this could be a number too, eg. from Date.getTime().
Here is using Array.filter, I don't think it's as fast a Object lookup's. But here we go.
var calendar = [
new Date('2016-09-01'),
new Date('2016-09-12'),
new Date('2016-09-10')
];
var finddate = new Date('2016-09-12');
var found = calendar.filter(function (a) { return a.getTime() === finddate.getTime();});
And if you don't mind using third party library, try underscore..
eg.
var days = [new Date('2016-09-01'), new Date('2016-09-10'), new Date('2016-09-30')];
var finddays = [new Date('2016-09-01'), new Date('2016-09-30')];
var found = _.intersectionWith(days, finddays,
function (a,b) { return a.getTime() === b.getTime(); });

Categories

Resources