How to compare dates to see where adjacent times meet? - javascript

I have dates currently formatted in the following way:
[ [ Tue Jun 17 2014 09:00:00 GMT-0400 (EDT),
Tue Jun 17 2014 10:00:00 GMT-0400 (EDT) ] ]
[ [ Thu Jun 19 2014 09:30:00 GMT-0400 (EDT),
Thu Jun 19 2014 11:30:00 GMT-0400 (EDT) ] ]
[ [ Tue Jun 17 2014 10:00:00 GMT-0400 (EDT),
Tue Jun 17 2014 11:00:00 GMT-0400 (EDT) ] ]
These dates are actually "sessions", and I need to see where certain sessions are adjacent to each other. For example, in this specific case, the first array of dates has a end time of 10AM while the last array of dates has a start time for 10AM. How can I computationally find this situation?
The one approach I have is to first sort the array sets from earliest time to to latest time, and then compare each of the start/end date pairs to see if they are the same, but I can't seem to get it through. Any ideas are welcome!

Turn the strings into Unix timestamps with Date.parse() (if these are actually Date objects, then use the .getTime() method) and then order the sessions with Array.prototype.sort(). Here's an example where the sessions are ordered by start time:
var sessions = [
["Tue Jun 17 2014 09:00:00 GMT-0400 (EDT)", "Tue Jun 17 2014 10:00:00 GMT-0400 (EDT)"],
["Thu Jun 19 2014 09:30:00 GMT-0400 (EDT)", "Thu Jun 19 2014 11:30:00 GMT-0400 (EDT)"],
["Tue Jun 17 2014 10:00:00 GMT-0400 (EDT)", "Tue Jun 17 2014 11:00:00 GMT-0400 (EDT)"]
];
for (var i = 0; i < sessions.length; i++) {
sessions[i].startTime= Date.parse(sessions[i][0]);
}
sessions.sort(function(a, b) { return a.startTime-b.startTime; });

Related

Transform date to wire format (YYYY-MM-DD) in javascript

Having this input: Wed Feb 03 2021 00:00:00 GMT+0200 (Eastern European Standard Time), is there a way to format it as YYYY-MM-DD, to it will become 2021-02-03?
Try this:
const date = moment(new Date('Wed Feb 03 2021 00:00:00 GMT+0200 (Eastern European Standard Time)')).format('YYYY-MM-DD');
console.log(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous"></script>
Parsing a timestamp to a date to reformat it may well produce incorrect results if the timestamp includes an offset or timezone. Given "Wed Feb 03 2021 00:00:00 GMT+0200 (Eastern European Standard Time)", for a user with an offset of +1 or less the date will be 2 Feb, not 3 Feb.
The most reliable method is to reformat the string, e.g.
let timestamp = "Wed Feb 03 2021 00:00:00 GMT+0200 (Eastern European Standard Time)";
let months = [,'Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'];
let pad = n=>('0'+n).slice(-2);
let p = timestamp.split(' ');
console.log(`${p[3]}-${pad(months.indexOf(p[1]))}-${p[2]}`);

Google Chart - arrayToDataTable not an array error

I have a backend in nodejs that generates an array and call a javascript function to plot a graph.
var data = google.visualization.arrayToDataTable(value)
The problem that I got a uncaught error:
Printing the variable value I have:
[ [ 'ml', 'date' ],
[ 'Sun Nov 24 2019 13:30:00 GMT-0200 (Brasilia Summer Time)',
481 ],
[ 'Sun Nov 24 2019 14:00:00 GMT-0200 (Brasilia Summer Time)',
571 ] ]
Reading similar posts like Google Chart - uncaught error: not an array i tried:
var data = google.visualization.arrayToDataTable(JSON.parse(values));
But i get the following error:
If I hardcode values it works fine:
var values = google.visualization.arrayToDataTable([
['ml','date'],
['Sun Nov 24 2019 13:30:00 GMT-0200 (Brasilia Summer Time)',481 ],
['Sun Nov 24 2019 14:00:00 GMT-0200 (Brasilia Summer Time)',571 ]
]);
var data = google.visualization.arrayToDataTable(values);
I couldn't see any difference printing the variable from hardcoding.
Any ideia?
the array is most likely being passed as a string.
if so, you need to use --> JSON.parse
but you need to swap the single quotes (') for double quotes (")
see following snippet, which works...
var test = JSON.parse('[["ml","date"],["Sun Nov 24 2019 13:30:00 GMT-0200 (Brasilia Summer Time)",481 ],["Sun Nov 24 2019 14:00:00 GMT-0200 (Brasilia Summer Time)",571 ]]');
console.log(test);
while this snippet does not...
var test = JSON.parse("[['ml','date'],['Sun Nov 24 2019 13:30:00 GMT-0200 (Brasilia Summer Time)',481 ],['Sun Nov 24 2019 14:00:00 GMT-0200 (Brasilia Summer Time)',571 ]]");
console.log(test);

Javascript vs Date

I have some interesting problem and can't find the solution. Look at this:
var d1 = new Date("07 31 2014");
document.write(d1);
document.write('<br />');
var d2 = new Date(1406746800 * 1000);
document.write(d2);
when I run this script I get this result:
Thu Jul 31 2014 00:00:00 GMT+0500 (UZT)
Thu Jul 31 2014 00:00:00 GMT+0500 (UZT)
then after I changed my time zone I get this result:
Thu Jul 31 2014 00:00:00 GMT-0800 (AKDT)
Wed Jul 30 2014 11:00:00 GMT-0800 (AKDT)
as you can see the second result is Jul 30, but first result is Jul 31. I think they must both be equal to 31 Jul. I know this problem depends on the timezone but is there a solution?
So the constructor parameter is:
an Integer value representing the number of milliseconds since 1
January 1970 00:00:00 UTC
So given your integer value, that represents (for me, in BST):
Wed Jul 30 2014 20:00:00 GMT+0100
Which is
Wed Jul 30 2014 19:00:00 UTC
And your timezone is GMT-8, so thats the above -8 which gives:
Wed Jul 30 2014 11:00:00 GMT-0800 AKDT
The date string constructor constructs the date in your local timezone. You can see what the value should be by doing this:
new Date("07 31 2014").getTime() / 1000
Which returns 1406761200, not 1406746800

Strange Date( )'s created with Strings containing NULL bytes

I know that JavaScript doesn't NULL terminate strings like C or C++ do, but I ran into a case which I can't explain.
Look at the following code (executed in Node.js v0.10.5) :
> new Date('123')
Fri Jan 01 123 00:00:00 GMT+0100 (CET) // UNIX epoch : -58285702800000
> new Date('123\056')
Fri Jan 01 123 00:00:00 GMT+0100 (CET) // UNIX epoch : -58285702800000
> new Date('123\0456')
Tue Jun 01 123 00:00:00 GMT+0200 (CEST) // UNIX epoch : -58272660000000
> new Date('123\0567')
Thu Jul 01 123 00:00:00 GMT+0200 (CEST) // UNIX epoch : -58270068000000
> new Date('123\0999')
Fri Jan 01 123 00:00:00 GMT+0100 (CET) // UNIX epoch : -58285702800000
> new Date('123\0555')
Sat May 01 123 00:00:00 GMT+0200 (CEST) // UNIX epoch : -58275338400000
> new Date('123\0655')
Sat Jan 01 12355 00:00:00 GMT+0100 (CET) // UNIX epoch : 327718911600000
I'm not sure what's happening here, can someone explain it to me ?
It would seem that sometimes, the integers after a NULL byte define the month of the date, but the month not always correspond to the following number.
Those are 3-digit octal escapes, not null bytes. So for example '123\0456' is realy '123%6'.

Sorting nested arrays of objects by date

I'm trying to sort an array that looks like this:
var dateGroups = [
[
{age:20, date: Fri Feb 03 2012 14:30:00 GMT+1100 (EST)},
{age:12, date: Fri Feb 03 2012 18:20:00 GMT+1100 (EST)},
{age:18, date: Fri Feb 03 2012 21:43:00 GMT+1100 (EST)}
],
[
{age:32, date: Fri Feb 01 2012 10:54:00 GMT+1100 (EST)},
{age:44, date: Fri Feb 01 2012 11:45:00 GMT+1100 (EST)},
],
[
{age:22, date: Fri Feb 05 2012 10:54:00 GMT+1100 (EST)},
{age:22, date: Fri Feb 05 2012 18:22:00 GMT+1100 (EST)},
]
]
The objects inside dateGroups' nested arrays are already sorted in ascending order, but I also want to sort the arrays themselves based on the grouped dates.
In this case the array should then look like this:
var dateGroups = [
[
{age:32, date: Fri Feb 01 2012 10:54:00 GMT+1100 (EST)},
{age:44, date: Fri Feb 01 2012 11:45:00 GMT+1100 (EST)},
],
[
{age:20, date: Fri Feb 03 2012 14:30:00 GMT+1100 (EST)},
{age:12, date: Fri Feb 03 2012 18:20:00 GMT+1100 (EST)},
{age:18, date: Fri Feb 03 2012 21:43:00 GMT+1100 (EST)}
],
[
{age:22, date: Fri Feb 05 2012 10:54:00 GMT+1100 (EST)},
{age:22, date: Fri Feb 05 2012 18:22:00 GMT+1100 (EST)},
]
]
The function used to sort should also return the new sorted version of dateGroups.
I've tried using Underscore.js's sortBy() function but I can't figure out how to sort the arrays based on the value of a property inside one of the objects. Is there a specific way to sort Date objects? Or are they sorted in the same way as numbers or letters?
According to Underscore.js documentation, you should simply write your own iterator for that cause. Something like this:
_.sortBy(dateGroups, function(arrayElement) {
//element will be each array, so we just return a date from first element in it
return arrayElement[0].date.getTime();
});
You can sort them by passing a custom sort function to Array.sort.
dateGroups.sort(function(a, b) {
return b[0].date.getTime() - a[0].date.getTime();
});
The custom function needs to return a number less than zero (a comes before b), greater than zero (a comes after b) or zero (a and b are equal).
As far as I understand your question, you want to sort the inner groups so that the early dates will be displayed first and then sort the groups by their first dates.
This could be done like this:
var sortedDateGroups = dateGroups.map(function(dateGroup) {
// sort the inner groups
dateGroup.sort(function(a,b) {
return a.date.getTime() - b.date.getTime();
});
return dateGroup;
}).sort(function(a,b) {
// sort the outer groups
return a[0].date.getTime() - b[0].date.getTime();
});
Of course this could be done with underscore js in a similar fashion:
var sortedDateGroups = _.chain(dateGroups).map(function(dateGroup) {
return _.sortBy(dateGroup, function(inner) {
return inner.date.getTime();
});
}).sortBy(function(outer) {
return outer[0].date.getTime();
}).value()
In case you have dates in string format, this worked for me:
yourArray.sort((a, b) => Date.parse(b[3]) - Date.parse(a[3]))

Categories

Resources