I am getting an array of dates in this format
Sat Feb 12 2022 01:00:00 GMT+0100 (West Africa Standard Time),Sun Feb 13 2022 01:00:00 GMT+0100 (West Africa Standard Time),Mon Feb 14 2022 01:00:00 GMT+0100 (West Africa Standard Time)
But i want it in a format like this
Sat, Feb 12, 2022,
Sun, Feb 13, 2022,
Mon, Feb 14, 2022
This is the code that output my date
function dateRange(startDate, endDate, steps = 1) {
const dateArray = [];
let currentDate = new Date(startDate);
while (currentDate <= new Date(endDate)) {
dateArray.push(new Date(currentDate));
currentDate.setUTCDate(currentDate.getUTCDate() + steps);
}
return dateArray;
}
var currD = new Date().toISOString().slice(0,10);
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
const futureDate = addDays(currD, 3);
const dates = dateRange(currD, futureDate);
console.log(dates);
alert(dates)
Try this
const dates = [
'Sat Feb 12 2022 01:00:00 GMT+0100 (West Africa Standard Time)',
'Sun Feb 13 2022 01:00:00 GMT+0100 (West Africa Standard Time)',
'Mon Feb 14 2022 01:00:00 GMT+0100 (West Africa Standard Time)',
];
const formatted = dates.map((date) => new Date(date).toDateString());
console.log(formatted);
Related
This is for a Google Sheet which uses GAS but I was advised to try Javascript Tag.
So I got this script which will read column 1 where I have the dates, and will group all rows by month and within these will group rows by day. This is because within each day I've got a row for every hour or 4 hours or so.
I need this script to also group by year as well. So it goes like:
Year Row -> Month Rows -> Day Rows
Month and day rows are working. I can't get the year grouping to work. Any ideas where to start?
The script:
function groupRow() {
const timeZone = "GMT+1";
const sheet = SpreadsheetApp.getActiveSheet();
const rowStart = 5;
const rows = sheet.getLastRow() - rowStart + 1;
const values = sheet.getRange(rowStart, 1, rows, 1).getValues().flat();
const o = [];
values.forEach((date, i) => {
const [m, d] = Utilities.formatDate(date, timeZone, "yyyyMM,dd").split(",");
if (!o[m]) {
o[m] = [];
}
if (!o[m][d]) {
o[m][d] = [];
}
o[m][d].push(rowStart + i);
});
for (var m in o) {
o[m] = Object.values(o[m]).sort((a,b) => parseInt(a) - parseInt(b));
}
Object.values(o).forEach(m => {
for (const d of m) {
if (d.length === 1) {
continue;
}
const range = `${ d[1] }:${ d.slice(-1)[0] }`;
sheet.getRange(range).shiftRowGroupDepth(1);
}
const a = m.flat();
if (a.length === 1) {
return;
}
const range = `${ a[1] }:${ a.slice(-1)[0] }`;
sheet.getRange(range).shiftRowGroupDepth(1);
});
}
Here's the link for dummy file:
https://docs.google.com/spreadsheets/d/1ExXtmQ8nyuV1o_UtabVJ-TifIbORItFMWjtN6ZlruWc/edit?usp=sharing
Well, it's me again. :) I can't sleep whenever there is some unsolved code.
It seems work to a degree:
function groupRow() {
var timeZone = "GMT+1";
var sheet = SpreadsheetApp.getActiveSheet();
var rowStart = 5;
var rows = sheet.getLastRow() - rowStart + 1;
var values = sheet.getRange(rowStart, 1, rows, 1).getValues().flat();
var o = {};
// make the object {'year': { 'month':[days] } }
values.forEach((date, i) => {
var [y, m, d] = Utilities.formatDate(date, timeZone, "yyyy,MM,dd").split(",");
// console.log(y, m, d);
if (!o[y]) o[y] = {};
if (!o[y][m]) o[y][m] = {};
if (!o[y][m][d]) o[y][m][d] = [];
o[y][m][d].push(rowStart + i);
});
// convert the unordered object {year:{month:[days]}}
// into the ordered 3d-array [year[month[days]]]
const numsort = (a,b) => parseInt(a) - parseInt(b);
var years = Object.keys(o).sort(numsort)
.map(y => Object.keys(o[y]).sort(numsort)
.map(m => Object.values(o[y][m]).sort(numsort)));
// group rows by years
years.forEach(y => shift_rows(y.map(m => m.flat()).flat(),sheet));
// group rows by months
years.flat().forEach(m => shift_rows(m.flat(),sheet));
// group rows by days
years.flat().flat().forEach(d => shift_rows(d.flat(),sheet));
function shift_rows(rows,sheet) {
if (rows.length === 1) return;
var range = `${ rows[1] }:${ rows.slice(-1) }`;
sheet.getRange(range).shiftRowGroupDepth(1);
}
}
But the code is really complicated already. It's need to test and... most likely, to rewrite it from scratch.
This approach to handling row groups tries to focus on readability/maintainability over efficiency, by minimizing array manipulation. If the code runs too slowly, then you can consider performance optimizations - but those can generally make the code harder to read.
It also tries to make the code easier to test by breaking it down into multiple separate functions, where each function tries to do as little logic as possible (I'm sure that could be improved & simplified, even further).
It makes 3 passes over the dates data, one for each type of grouping (year, month, and date). That's the big compromise vs. efficiency.
I've presented it here as a runnable snippet with some hard-coded data, not as a full GAS script, since the core of the logic is pure JavaScript.
var src_data = [
'Thu Aug 26 2021 21:27:26 GMT-0400 (Eastern Daylight Time)',
'Fri Aug 27 2021 21:27:26 GMT-0400 (Eastern Daylight Time)',
'Fri Aug 27 2021 23:51:26 GMT-0400 (Eastern Daylight Time)',
'Sun Aug 29 2021 09:27:26 GMT-0400 (Eastern Daylight Time)',
'Sat Sep 04 2021 07:03:26 GMT-0400 (Eastern Daylight Time)',
'Sat Sep 04 2021 16:39:26 GMT-0400 (Eastern Daylight Time)',
'Fri Sep 17 2021 00:49:02 GMT-0400 (Eastern Daylight Time)',
'Fri Sep 17 2021 03:13:02 GMT-0400 (Eastern Daylight Time)',
'Wed Sep 22 2021 03:13:02 GMT-0400 (Eastern Daylight Time)',
'Tue Sep 28 2021 03:13:02 GMT-0400 (Eastern Daylight Time)',
'Wed Sep 29 2021 11:22:38 GMT-0400 (Eastern Daylight Time)',
'Wed Sep 29 2021 12:34:38 GMT-0400 (Eastern Daylight Time)',
'Mon Oct 11 2021 12:34:38 GMT-0400 (Eastern Daylight Time)',
'Tue Oct 12 2021 19:46:38 GMT-0400 (Eastern Daylight Time)',
'Thu Nov 04 2021 19:46:38 GMT-0400 (Eastern Daylight Time)',
'Mon Nov 29 2021 09:13:02 GMT-0500 (Eastern Standard Time)',
'Thu Dec 23 2021 22:39:26 GMT-0500 (Eastern Standard Time)',
'Mon Jan 17 2022 12:05:50 GMT-0500 (Eastern Standard Time)',
'Fri Feb 11 2022 01:32:14 GMT-0500 (Eastern Standard Time)',
'Mon Mar 07 2022 14:58:38 GMT-0500 (Eastern Standard Time)',
'Mon Mar 07 2022 14:58:39 GMT-0500 (Eastern Standard Time)'
];
var dates = src_data.map(d => new Date(d));
// The starting row of our data in the spreadsheet:
var rowStart = 5;
// We will compare each new date against the previous date to see
// if the period has changed:
var prevDate;
// Build a range of potentially groupable dates, because they share the
// same period. These are the array range start & end positions:
var rangeStart;
var rangeEnd;
// the type of grouping to create:
var groupingPeriod;
//
// entry point:
//
groupDates('year');
groupDates('month');
groupDates('date');
// process the array of dates:
function groupDates(period) {
groupingPeriod = period;
console.log('finding groups by ' + period + ':') ;
dates.forEach((date, idx) => {
// The first date is a special case:
if (idx === 0) {
processInitialDate(date);
} else {
// everything which is not the first date:
processDate(date, idx);
}
} );
}
// Some initial set-up (and we know we cannot create
// a group containing only the first date):
function processInitialDate(date) {
prevDate = date;
rangeStart = 0;
rangeEnd = rangeStart;
}
// All dates except the first one:
function processDate(date, idx) {
if (periodHasChanged(date, prevDate, groupingPeriod)) {
createGroup();
// start a new range:
rangeStart = rangeEnd +1;
rangeEnd = rangeStart;
} else {
// extend the current range:
rangeEnd++;
// the final value in the array is a special case, which
// would otherwise not be processed (because there is no
// "next" date to compare it against):
if (idx === dates.length -1) {
createGroup();
}
}
prevDate = date;
}
function periodHasChanged(currDate, prevDate, period) {
switch(period) {
case 'year':
var currPeriod = currDate.getYear();
var prevPeriod = prevDate.getYear();
break;
case 'month':
var currPeriod = currDate.getMonth();
var prevPeriod = prevDate.getMonth();
break;
case 'date':
var currPeriod = currDate.getDate();
var prevPeriod = prevDate.getDate();
break;
}
return currPeriod !== prevPeriod;
}
function createGroup() {
var rangeGroup = dates.slice(rangeStart, rangeEnd +1);
// only create the group if it contains at least 2 dates:
if (rangeGroup.length > 1) {
// make the group here - but for testing, we just log it to the console:
// TODO - build the sheet range, by adjusting the array rangeStart
// and rangeEnd values, using the rowStart value defined earlier.
//range.shiftRowGroupDepth(1);
console.log( rangeGroup );
}
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
</body>
</html>
Here is the full GAS script I used:
function groupingDemo() {
//const timeZone = "GMT+1";
rowStart = 5;
sheet = SpreadsheetApp.getActiveSheet();
rows = sheet.getLastRow() - rowStart + 1;
dates = sheet.getRange(rowStart, 1, rows, 1).getValues().flat();
groupDates(dates, 'year');
groupDates(dates, 'month');
groupDates(dates, 'date');
}
// spreadsheet items:
var sheet;
var rowStart;
var dates;
// We will compare each new date against the previous date to see
// if the period has changed:
var prevDate;
// Build a range of potentially groupable dates, because they share the
// same period. These are the array range start & end positions:
var rangeStart;
var rangeEnd;
// the type of grouping to create:
var groupingPeriod;
// process the array of dates:
function groupDates(dates, period) {
groupingPeriod = period;
console.log('finding groups by ' + period + ':') ;
dates.forEach((date, idx) => {
// The first date is a special case:
if (idx === 0) {
processInitialDate(date);
} else {
// everything which is not the first date:
processDate(date, idx);
}
} );
}
// Some initial set-up (and we know we cannot create
// a group containing only the first date):
function processInitialDate(date) {
prevDate = date;
rangeStart = 0;
rangeEnd = rangeStart;
}
// All dates except the first one:
function processDate(date, idx) {
if (periodHasChanged(date, prevDate, groupingPeriod)) {
createGroup();
// start a new range:
rangeStart = rangeEnd +1;
rangeEnd = rangeStart;
} else {
// extend the current range:
rangeEnd++;
// the final value in the array is a special case, which
// would otherwise not be processed (because there is no
// "next" date to compare it against):
if (idx === dates.length -1) {
createGroup();
}
}
prevDate = date;
}
function periodHasChanged(currDate, prevDate, period) {
switch(period) {
case 'year':
var currPeriod = currDate.getYear();
var prevPeriod = prevDate.getYear();
break;
case 'month':
var currPeriod = currDate.getMonth();
var prevPeriod = prevDate.getMonth();
break;
case 'date':
var currPeriod = currDate.getDate();
var prevPeriod = prevDate.getDate();
break;
}
return currPeriod !== prevPeriod;
}
function createGroup() {
const sheet = SpreadsheetApp.getActiveSheet();
var rangeGroup = dates.slice(rangeStart, rangeEnd +1);
// only create the group if it contains at least 2 dates:
if (rangeGroup.length > 1) {
// make a new group (we use the "+1" to avoid contiguous groups being merged):
var range = `${ rowStart + rangeStart +1 }:${ rowStart + rangeEnd }`;
sheet.getRange(range).shiftRowGroupDepth(1);
// uncomment these to see what's going on:
//console.log( rangeGroup );
//console.log( 'sheet rows: ' + `${ rowStart + rangeStart +1 }:${ rowStart + rangeEnd }` )
}
}
The results:
And if you un-comment the logging statements, you see the following logs:
finding groups by year:
[ Thu Aug 26 2021 21:27:26 GMT-0400 (Eastern Daylight Time),
Fri Aug 27 2021 21:27:26 GMT-0400 (Eastern Daylight Time),
Fri Aug 27 2021 23:51:26 GMT-0400 (Eastern Daylight Time),
Sun Aug 29 2021 09:27:26 GMT-0400 (Eastern Daylight Time),
Sat Sep 04 2021 07:03:26 GMT-0400 (Eastern Daylight Time),
Sat Sep 04 2021 16:39:26 GMT-0400 (Eastern Daylight Time),
Fri Sep 17 2021 00:49:02 GMT-0400 (Eastern Daylight Time),
Fri Sep 17 2021 03:13:02 GMT-0400 (Eastern Daylight Time),
Wed Sep 22 2021 03:13:02 GMT-0400 (Eastern Daylight Time),
Tue Sep 28 2021 03:13:02 GMT-0400 (Eastern Daylight Time),
Wed Sep 29 2021 11:22:38 GMT-0400 (Eastern Daylight Time),
Wed Sep 29 2021 12:34:38 GMT-0400 (Eastern Daylight Time),
Mon Oct 11 2021 12:34:38 GMT-0400 (Eastern Daylight Time),
Tue Oct 12 2021 19:46:38 GMT-0400 (Eastern Daylight Time),
Thu Nov 04 2021 19:46:38 GMT-0400 (Eastern Daylight Time),
Mon Nov 29 2021 09:13:02 GMT-0500 (Eastern Standard Time),
Thu Dec 23 2021 22:39:26 GMT-0500 (Eastern Standard Time) ]
sheet rows: 6:21
[ Mon Jan 17 2022 12:05:50 GMT-0500 (Eastern Standard Time),
Fri Feb 11 2022 01:32:14 GMT-0500 (Eastern Standard Time),
Mon Mar 07 2022 14:58:38 GMT-0500 (Eastern Standard Time) ]
sheet rows: 23:24
finding groups by month:
[ Thu Aug 26 2021 21:27:26 GMT-0400 (Eastern Daylight Time),
Fri Aug 27 2021 21:27:26 GMT-0400 (Eastern Daylight Time),
Fri Aug 27 2021 23:51:26 GMT-0400 (Eastern Daylight Time),
Sun Aug 29 2021 09:27:26 GMT-0400 (Eastern Daylight Time) ]
sheet rows: 6:8
[ Sat Sep 04 2021 07:03:26 GMT-0400 (Eastern Daylight Time),
Sat Sep 04 2021 16:39:26 GMT-0400 (Eastern Daylight Time),
Fri Sep 17 2021 00:49:02 GMT-0400 (Eastern Daylight Time),
Fri Sep 17 2021 03:13:02 GMT-0400 (Eastern Daylight Time),
Wed Sep 22 2021 03:13:02 GMT-0400 (Eastern Daylight Time),
Tue Sep 28 2021 03:13:02 GMT-0400 (Eastern Daylight Time),
Wed Sep 29 2021 11:22:38 GMT-0400 (Eastern Daylight Time),
Wed Sep 29 2021 12:34:38 GMT-0400 (Eastern Daylight Time) ]
sheet rows: 10:16
[ Mon Oct 11 2021 12:34:38 GMT-0400 (Eastern Daylight Time),
Tue Oct 12 2021 19:46:38 GMT-0400 (Eastern Daylight Time) ]
sheet rows: 18:18
[ Thu Nov 04 2021 19:46:38 GMT-0400 (Eastern Daylight Time),
Mon Nov 29 2021 09:13:02 GMT-0500 (Eastern Standard Time) ]
sheet rows: 20:20
finding groups by date:
[ Fri Aug 27 2021 21:27:26 GMT-0400 (Eastern Daylight Time),
Fri Aug 27 2021 23:51:26 GMT-0400 (Eastern Daylight Time) ]
sheet rows: 7:7
[ Sat Sep 04 2021 07:03:26 GMT-0400 (Eastern Daylight Time),
Sat Sep 04 2021 16:39:26 GMT-0400 (Eastern Daylight Time) ]
sheet rows: 10:10
[ Fri Sep 17 2021 00:49:02 GMT-0400 (Eastern Daylight Time),
Fri Sep 17 2021 03:13:02 GMT-0400 (Eastern Daylight Time) ]
sheet rows: 12:12
[ Wed Sep 29 2021 11:22:38 GMT-0400 (Eastern Daylight Time),
Wed Sep 29 2021 12:34:38 GMT-0400 (Eastern Daylight Time) ]
sheet rows: 16:16
I have start and end properties in range object. And each property has time value.
range = {
start: Tue Jul 07 2020 10:58:05,
end: Wed Jul 08 2020 10:58:05
}
then I have to make an array of length 30 that contains random time between range.start and range.end.
[Tue Jul 07 2020 11:00:05, Tue Jul 07 2020 13:49:12, Tue Jul 07 2020 15:22:54... Wed Jul 08 2020 12:51:05, Wed Jul 08 2020 15:24:13]
I think I can do it using new Array(30).fill(dates) but have no clue what to put it inside dates.
This converts your dates to timestamps, then generates random numbers in-between and converts those back to dates. Note: added timezone
var start = new Date('Tue Jul 07 2020 10:58:05 GMT-0400').getTime();
var end = new Date('Wed Jul 08 2020 10:58:05 GMT-0400').getTime();
var dates = Array(30).fill().map(() => {
return new Date(
Math.floor(Math.random() * (end - start)) + start
).toString();
});
Results in:
["Wed Jul 08 2020 01:55:53 GMT-0400 (Eastern Daylight Time)"
"Tue Jul 07 2020 16:58:52 GMT-0400 (Eastern Daylight Time)"
"Wed Jul 08 2020 00:02:45 GMT-0400 (Eastern Daylight Time)"
"Tue Jul 07 2020 15:33:55 GMT-0400 (Eastern Daylight Time)"
"Tue Jul 07 2020 20:16:20 GMT-0400 (Eastern Daylight Time)"
"Tue Jul 07 2020 15:25:33 GMT-0400 (Eastern Daylight Time)"
"Tue Jul 07 2020 17:15:14 GMT-0400 (Eastern Daylight Time)"
"Wed Jul 08 2020 02:20:32 GMT-0400 (Eastern Daylight Time)"
"Tue Jul 07 2020 23:25:54 GMT-0400 (Eastern Daylight Time)"
...]
Edit: for unique dates you can do something like this:
var start = new Date('Tue Jul 07 2020 10:58:05 GMT-0400').getTime();
var end = new Date('Wed Jul 08 2020 10:58:05 GMT-0400').getTime();
var dates = [];
while(dates.length < 30) {
let date = new Date(
Math.floor(Math.random() * (end - start)) + start
).toString();
if (!dates.includes(date)) {
dates.push(date);
}
}
I wouldn't use this if the start and end dates are very close (within seconds of eachother) and/or the output array is very large. It will block thread.
I'm not big fan of Array(n).fill() just to create an empty array with n undefined elements as the basis for a loop when the array is then discarded.
A for loop is likely less code and more efficient, e.g. (same algorithm as GitGitBoom):
let range = {
start: new Date(2020,6,7,10,58,05),
end: new Date(2020,6,8,10,58,05)
}
let result = [];
for (let s = +range.start, diff = range.end - s, i = 30; i; --i) {
result.push(new Date(s + Math.random() * diff).toString());
}
console.log(result.sort());
If you're prepared to use var, the result array can be declared in the for loop initialiser too.
Assuming you have a randomTimeGenerator, function:
var randomTimes = [];
var i=30; while(i--){randomTimes.push(randomTimeGenerator(i, randomTimes))}
here i have a json data given format
var data = [Mon Jul 16 2018 21:54:14 GMT+0530 (India Standard Time), Mon Jul 16 2018 21:54:14 GMT+0530 (India Standard Time)]
and how can i convert it into
classname(20180716,20180716)
i tried using split method for converting the data into array but i failed any suggestions
i followed join and split methods also
function convert(str) {
var date = new Date(str),
mnth = ("0" + (date.getMonth()+1)).slice(-2),
day = ("0" + date.getDate()).slice(-2);
return [ date.getFullYear(), mnth, day ].join("-");
}
convert("Thu Jun 09 2018 00:00:00 GMT+0530 (India Standard Time)");
Use the data as below:
var data = [
"Mon Jul 16 2018 21:54:14 GMT+0530 (India Standard Time)",
"Mon Jul 16 2018 21:54:14 GMT+0530 (India Standard Time)"
];
Separating the lines using a semi-colon works for me:
function convert(str) {
var date = new Date(str);
var mnth = ("0" + (date.getMonth() + 1)).slice(-2);
var day = ("0" + date.getDate()).slice(-2);
return [date.getFullYear(), mnth, day].join("-");
}
console.log(convert("Thu Jun 09 2018 00:00:00 GMT+0530 (India Standard Time)"));
The key is to declare date separately.
Output:
2018-06-08
To do for an array of all dates:
function convert(str) {
var date = new Date(str);
var mnth = ("0" + (date.getMonth() + 1)).slice(-2);
var day = ("0" + date.getDate()).slice(-2);
return [date.getFullYear(), mnth, day].join("-");
}
var data = [
"Mon Jul 16 2018 21:54:14 GMT+0530 (India Standard Time)",
"Mon Jul 16 2018 21:54:14 GMT+0530 (India Standard Time)"
];
console.log(data.map(convert));
Also note that the data should contain array of strings.
I currently have two arrays containing dates. I want to check if there's at least one match of values when comparing the two arrays. To clarify, these are Date objects and not strings. My code below always seems to return false:
var between = [Sun Aug 27 2017 00:00:00 GMT+0100 (BST), Mon Aug 28 2017 00:00:00 GMT+0100 (BST), Tue Aug 29 2017 00:00:00 GMT+0100 (BST), Wed Aug 30 2017 00:00:00 GMT+0100 (BST)];
var myDate = [Mon Aug 28 2017 00:00:00 GMT+0100 (BST), Thu Aug 24 2017 00:00:00 GMT+0100 (BST)];
var bExists = false;
$.each(myDate, function(index, value){
if($.inArray(value,between)!=-1){
console.log(value);
bExists = true;
}
if(bExists){
return false; //break
}
});
console.log(bExists);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In this way you can find the one's that match
Array.prototype.diff = function(arr2) {
var ret = [];
for(var i in this) {
if(arr2.indexOf( this[i] ) > -1){
ret.push( this[i] );
}
}
return ret;
};
You can make use of .some of Array to check at least one element satisfy the condition.
var between = ["Sun Aug 27 2017 00:00:00 GMT+0100 (BST)", "Mon Aug 28 2017 00:00:00 GMT+0100 (BST)", "Tue Aug 29 2017 00:00:00 GMT+0100 (BST)", "Wed Aug 30 2017 00:00:00 GMT+0100 (BST)"];
var myDate = ["Mon Aug 28 2017 00:00:00 GMT+0100 (BST)", "Thu Aug 24 2017 00:00:00 GMT+0100 (BST)"];
//checking atleast one present
var atleastOne = myDate.some(function(item){
return between.indexOf(item) > -1;
});
//checking that all present
var all = myDate.every(function(item){
return between.indexOf(item) > -1;
});
console.log(all);
var between = [Sun Aug 27 2017 00:00:00 GMT+0100 (BST), Mon Aug 28 2017 00:00:00 GMT+0100 (BST), Tue Aug 29 2017 00:00:00 GMT+0100 (BST), Wed Aug 30 2017 00:00:00 GMT+0100 (BST)];
var myDate = [Mon Aug 28 2017 00:00:00 GMT+0100 (BST), Thu Aug 24 2017 00:00:00 GMT+0100 (BST)];
var bExists = false;
for ( var i = 0; i < between.length; i++ ) {
for ( var e = 0; e < myDate.length; e++ ) {
if ( between[i] === myDate[e] ){
bExists = true;
}
}
console.log(bExists);
You could use Array.some()
The some() method tests whether at-least one element in the array passes the test implemented by the provided function.
var between = ['Sun Aug 27 2017 00:00:00 GMT+0100 (BST)', 'Mon Aug 28 2017 00:00:00 GMT+0100 (BST)','Tue Aug 29 2017 00:00:00 GMT+0100 (BST)', 'Wed Aug 30 2017 00:00:00 GMT+0100 (BST)'];
var myDate = ['Mon Aug 28 2017 00:00:00 GMT+0100 (BST)', 'Thu Aug 24 2017 00:00:00 GMT+0100 (BST)'];
console.log(between.some(date => myDate.includes(date)));
var between = ['Sun Aug 27 2017 00:00:00 GMT+0100 (BST)', 'Mon Aug 28 2017 00:00:00 GMT+0100 (BST)', 'Tue Aug 29 2017 00:00:00 GMT+0100 (BST)', 'Wed Aug 30 2017 00:00:00 GMT+0100 (BST)'];
var myDate = ['Mon Aug 28 2017 00:00:00 GMT+0100 (BST)', 'Thu Aug 24 2017 00:00:00 GMT+0100 (BST)'];
var isExist = false;
//checking atleast one present
$.each(myDate ,function(index , value){
if(between.indexOf(value) != "-1")
{
isExist = true;
return;
}
});
console.log(isExist);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var between = [new Date('Sun Aug 27 2017 00:00:00 GMT+0100 (BST)'), new Date('Mon Aug 28 2017 00:00:00 GMT+0100 (BST)'), new Date('Tue Aug 29 2017 00:00:00 GMT+0100 (BST)'), new Date('Wed Aug 30 2017 00:00:00 GMT+0100 (BST)')];
var myDate = [new Date('Mon Aug 28 2017 00:00:00 GMT+0100 (BST)'), new Date('Thu Aug 24 2017 00:00:00 GMT+0100 (BST)')];
var bExists = false;
$.each(myDate, function(index, myDateValue){
$.each(between, function(index, betweenValue){
if(myDateValue.toString() == betweenValue.toString()){
console.log(betweenValue);
bExists = true;
return false;
}
})
});
console.log(bExists);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Convert your Date object toString or else you can use getTime and then compare.
I am building a timetable function, for that I have to insert the data week wise in an collection.
So I'm creating a array which will contain the weeks from start_date to end_date.
1st Push in an array: start_date = Declared date (if declared date is Sunday, then it consider the date of coming Monday); end_date = date on Saturday
2nd till nth Push in an array: start_date = date on Monday; end_date = date on Saturday or declared end date if its within the week
var start = new Date("09/30/2016");
var end = new Date("11/2/2016");
var count = 0;
var sDate;
var eDate;
var dateArr = [];
while(start <= end){
if (start.getDay() == 0){
count = 0;
}else {
if(count == 0){
sDate = start;
count = 1
}else {
count = 1;
}
if(start.getDay() == 6 || start == end){
count = 1
eDate = start;
}else {
count = 1;
}
if(sDate && eDate){
sDate = new Date(sDate)
eDate = new Date(eDate)
dateArr.push({'startDate': sDate, 'endDate': eDate});
sDate = undefined;
eDate = undefined;
}
}
var newDate = start.setDate(start.getDate() + 1);
start = new Date(newDate);
}
But the result Im getting is this
[{
'startDate':Sat Oct 01 2016 00:00:00 GMT+0530 (IST),
'endDate':Sat Oct 01 2016 00:00:00 GMT+0530 (IST),
},
{
'startDate':Tue Oct 04 2016 00:00:00 GMT+0530 (IST),
'endDate':Sat Oct 08 2016 00:00:00 GMT+0530 (IST),
},
{
'startDate':Tue Oct 11 2016 00:00:00 GMT+0530 (IST),
'endDate':Sat Oct 15 2016 00:00:00 GMT+0530 (IST),
},
{
'startDate':Tue Oct 18 2016 00:00:00 GMT+0530 (IST),
'endDate':Sat Oct 22 2016 00:00:00 GMT+0530 (IST),
},
{
'startDate':Tue Oct 25 2016 00:00:00 GMT+0530 (IST),
'endDate':Sat Oct 29 2016 00:00:00 GMT+0530 (IST),
}]
Edit:
Expected Result:
[{
'startDate':Fri Sep 30 2016 00:00:00 GMT+0530 (IST),
'endDate':Sat Oct 01 2016 00:00:00 GMT+0530 (IST),
},
{
'startDate':Mon Oct 03 2016 00:00:00 GMT+0530 (IST),
'endDate':Sat Oct 08 2016 00:00:00 GMT+0530 (IST),
},
{
'startDate':Mon Oct 10 2016 00:00:00 GMT+0530 (IST),
'endDate':Sat Oct 15 2016 00:00:00 GMT+0530 (IST),
},
{
'startDate':Mon Oct 17 2016 00:00:00 GMT+0530 (IST),
'endDate':Sat Oct 22 2016 00:00:00 GMT+0530 (IST),
},
{
'startDate':Mon Oct 24 2016 00:00:00 GMT+0530 (IST),
'endDate':Sat Oct 29 2016 00:00:00 GMT+0530 (IST),
},
{
'startDate':Mon Oct 31 2016 00:00:00 GMT+0530 (IST)
'endDate':Wed Nov 02 2016 00:00:00 GMT+0530 (IST),
}]
Check this out. I fixed some logical and obj reference errors.
var start = new Date(Date.UTC(2016, 09, 30, 0, 0, 0));
var end = new Date(Date.UTC(2016, 11, 02, 0, 0, 0));
var sDate;
var eDate;
var dateArr = [];
while(start <= end){
if (start.getDay() == 1 || (dateArr.length == 0 && !sDate)){
sDate = new Date(start.getTime());
}
if ((sDate && start.getDay() == 0) || start.getTime() == end.getTime()){
eDate = new Date(start.getTime());
}
if(sDate && eDate){
dateArr.push({'startDate': sDate, 'endDate': eDate});
sDate = undefined;
eDate = undefined;
}
start.setDate(start.getDate() + 1);
}
console.log(dateArr);
https://jsfiddle.net/c58zde4b/6/
The displayed date may vary due to your local timezone settings.