How to calculate max number using node.js? - javascript

In my node script I have the following function, which determines max date:
if (result.rows.length > 0) {
var maxDate = new Date(
result.rows.map(o => o.REPORTED_DATE).reduce(function(a, b) {
return Math.max(a, Date.parse(b));
})
);
}
The REPORTED_DATE used to be a date, but now it changed to the unix epoch, which is a 10-digit number.
What is the proper syntax to determine max number instead of the date?

If REPORTED_DATE is now a number then you should be able to simply remove the Date.parse() call within your existing .reduce() function:
return Math.max(a, b);
However, given that Math.max() can handle any number of arguments you don't need to use .reduce(), you can instead just use .apply() to pass Math.max() the array of numbers that you're producing with .map():
Math.max.apply(null, result.rows.map(o => o.REPORTED_DATE))
If the REPORTED_DATE is a Unix-style 10-digit number then that is number of seconds, so you'd need to multiple it by 1000 to get milliseconds for conversion to a JavaScript Date object. So putting that together in context:
if (result.rows.length > 0) {
var maxDate = new Date(
Math.max.apply(null, result.rows.map(o => o.REPORTED_DATE)) * 1000
);
}

Related

cannot compare dates for some reason [duplicate]

When comparing date objects in Javascript I found that even comparing the same date does not return true.
var startDate1 = new Date("02/10/2012");
var startDate2 = new Date("01/10/2012");
var startDate3 = new Date("01/10/2012");
alert(startDate1>startDate2); // true
alert(startDate2==startDate3); //false
How could I compare the equality of these dates? I am interested in utilizing the native Date object of JS and not any third party libraries since its not appropriate to use a third party JS just to compare the dates.
That is because in the second case, the actual date objects are compared, and two objects are never equal to each other. Coerce them to number:
alert( +startDate2 == +startDate3 ); // true
If you want a more explicity conversion to number, use either:
alert( startDate2.getTime() == startDate3.getTime() ); // true
or
alert( Number(startDate2) == Number(startDate3) ); // true
Oh, a reference to the spec: §11.9.3 The Abstract Equality Comparison Algorithm which basically says when comparing objects, obj1 == obj2 is true only if they refer to the same object, otherwise the result is false.
Compare dates using getTime() returning number of milliseconds from epoch (i.e. a number):
var startDate1 = new Date("02/10/2012");
var startDate2 = new Date("01/10/2012");
var startDate3 = new Date("01/10/2012");
alert(startDate1.getTime() > startDate2.getTime()); // true
alert(startDate2.getTime() == startDate3.getTime()); //true
Also consider using Date constructor taking explicit year/month/date number rather then relying on string representation (see: Date.parse()). And remember that dates in JavaScript are always represented using client (browser) timezone.
You do not need to use the getTime method- you can subtract a date object from another date object. It will return the milliseconds difference(negative, if the second is a later date)
var startDate1 = new Date("02/10/2012");
var startDate2 = new Date("01/10/2012");
var diff= (startDate1 -startDate2)
// evaluates to 0 if the dates have the same timestamp
you can compare the actual milliseconds :
alert(startDate2.getTime() === startDate3.getTime());
tl;dr
Use date.getTime() for comparisons.
Based on my testing, it was at least 25% than the next fastest alternative (date.valueOf()).
Details
Came across this in 2022. As others have already said, comparing like date1.getTime() === date2.getTime() is the way to go.
Someone else shared a jsperf link in an answer that seems broken for me right now, so decided to add some performance comparison of my own.
I created two arrays containing 1000 dates each. All dates will naturally be different instances (meaning direct === checks will fail), so what this benchmark does, is test what the fastest way is to convert a date to a primitive.
Here's the test data:
const data1 = Array.from({length: 1000}, () => new Date())
const data2 = Array.from({length: 1000}, () => new Date())
And here are the test cases (there's more in the link below):
// 1
data1.forEach((d1, i) => d1.getTime() === data2[i].getTime());
// 2
data1.forEach((d1, i) => d1.valueOf() === data2[i].valueOf());
// 3
data1.forEach((d1, i) => Number(d1) === Number(data2[i]));
// 4
data1.forEach((d1, i) => d1.toISOString() === data2[i].toISOString());
Result (use date.getTime())
Not a surprise that a date.getTime() conversion is much faster. It's around 25% faster than date.valueOf(), and between 10x and 100x faster than everything else (as far as I've checked).
Additionally, introducing optional chaining slowed the best case by almost 10% for me. Found that interesting. date.valueOf() also slowed down by 5% compared to its non optional chaining counterpart.
data1.forEach((d1, i) => d1?.getTime() === data2[i]?.getTime());
Benchmark link: here
Here's an image, in case the above link breaks at some point in the future.
You can also use the function valueOf()
var startDate1 = new Date("02/10/2012").valueOf();
var startDate2 = new Date("01/10/2012").valueOf();
var startDate3 = new Date("01/10/2012").valueOf();
alert(startDate1>startDate2); // 1326150000000 > 1328828400000 true
alert(startDate2==startDate3); // 1328828400000 > 1326150000000 false
One more way of comparing two dates would be converting dates to timestamps using "+" operator before the date.
So, let's say we have two dates:
const dateOne = new Date("10 January 1986")
const dateTwo = new Date("10 December 2020")
if(+dateOne == +dateTwo){
//do something
}
and so on.
This is really handy if you are sorting date objects too as you can use this in the sorting callback function.

Sorting array by date and time in same time?

I am building shedule app, so i need to sort items by date and time in same time. Like you see in example i can only filter hours and minuts and that works, but i need to filter dates too
I am storing date in datebase like YYYY-MM-DD and time by hours and minuts like string for example: hours:"08",minuts:"25".
this.ord3ref.on("child_added", data => {
this.ord3.push({
key: data.key,
data: data.val()
});
this.ord3.sort(
(a, b) => a.data.hours- b.data.hours || a.data.minuts- b.data.minuts
);
});
like you see on image it sorts array by hours and minuts, but its need to be sorted by dates first, than with hours and minuts...
If the data contains a key/value for date then you should be able to just substitute your sort function with this:
this.ord3.sort(
(a, b) => {
var dateA = new Date(a.data.date).valueOf();
var dateB = new Date(b.data.date).valueOf();
return a.data.hours - b.data.hours || a.data.minuts - b.data.minuts || dateA - dateB;
}
);
javascript Date objects can be created from the date strings in the format YYYY-MM-DD.
The .valueOf() method returns the number of milliseconds from UTC time - see MDN's explanation of it.

Javascript Cannot use .now() on date string

So I wanted to compare two dates inside a post object. I tried to compare the date objects, but that returned NaN. Then I tried converting it to milliseconds since 1970 by using .now() on these dates, but it returned the following error:
It happens: TypeError: a.date.now is not a function
I tried typeof a.date and this returned string. I don't know why I can't use the .now() method. Can someone help me?
the whole function inside of angular service
getPosts(section) {
return this.http.get(url + '/forum/getPosts/' + section )
.map( (posts: any) => {
// posts should be ordened based on latest replies. If there are no replies yet, we compare it to the date
// of the original post
posts.obj.sort((a, b) => {
const aHasReplies = a.replies.length !== 0;
const bHasReplies = b.replies.length !== 0;
if (aHasReplies && bHasReplies ) {
return a.replies.slice(-1, 1)[0].date - b.replies.slice(-1, 1)[0].date;
} else if ( aHasReplies && !bHasReplies) {
return a.replies.slice(-1, 1)[0].date - b.date;
} else if ( !aHasReplies && bHasReplies) {
return a.date - b.replies.slice(-1, 1)[0].date;
} else {
console.log(a.date.now());
return a.date - b.date;
}
});
return posts;
});
}
It should be object, not string, if that's what you meant, because there is no "date string".
Other than that try:
new Date(a.date).getTime()
Because .now is a static method, you always use it as Date.now()
This means, that Date.now() always returns milliseconds elapsed since the UNIX epoch.
For converting to unix time use getTime.
If you want to compare them, compare two dates without conversion.
But keep in mind, that unix time is in seconds, and javascript method return in milliseconds. If you need exactly unix time, divide by 1000.
You can compare two dates in the year-month-day format (yyyy-mm-dd) using regular javascript comparators such as < and > etc
I suggest use moment.js library (https://momentjs.com/docs/) to parse Date from String.
So you can have some thing like
let date = moment(a.date)

how to use findIndex javascript method with date object? [duplicate]

When comparing date objects in Javascript I found that even comparing the same date does not return true.
var startDate1 = new Date("02/10/2012");
var startDate2 = new Date("01/10/2012");
var startDate3 = new Date("01/10/2012");
alert(startDate1>startDate2); // true
alert(startDate2==startDate3); //false
How could I compare the equality of these dates? I am interested in utilizing the native Date object of JS and not any third party libraries since its not appropriate to use a third party JS just to compare the dates.
That is because in the second case, the actual date objects are compared, and two objects are never equal to each other. Coerce them to number:
alert( +startDate2 == +startDate3 ); // true
If you want a more explicity conversion to number, use either:
alert( startDate2.getTime() == startDate3.getTime() ); // true
or
alert( Number(startDate2) == Number(startDate3) ); // true
Oh, a reference to the spec: §11.9.3 The Abstract Equality Comparison Algorithm which basically says when comparing objects, obj1 == obj2 is true only if they refer to the same object, otherwise the result is false.
Compare dates using getTime() returning number of milliseconds from epoch (i.e. a number):
var startDate1 = new Date("02/10/2012");
var startDate2 = new Date("01/10/2012");
var startDate3 = new Date("01/10/2012");
alert(startDate1.getTime() > startDate2.getTime()); // true
alert(startDate2.getTime() == startDate3.getTime()); //true
Also consider using Date constructor taking explicit year/month/date number rather then relying on string representation (see: Date.parse()). And remember that dates in JavaScript are always represented using client (browser) timezone.
You do not need to use the getTime method- you can subtract a date object from another date object. It will return the milliseconds difference(negative, if the second is a later date)
var startDate1 = new Date("02/10/2012");
var startDate2 = new Date("01/10/2012");
var diff= (startDate1 -startDate2)
// evaluates to 0 if the dates have the same timestamp
you can compare the actual milliseconds :
alert(startDate2.getTime() === startDate3.getTime());
tl;dr
Use date.getTime() for comparisons.
Based on my testing, it was at least 25% than the next fastest alternative (date.valueOf()).
Details
Came across this in 2022. As others have already said, comparing like date1.getTime() === date2.getTime() is the way to go.
Someone else shared a jsperf link in an answer that seems broken for me right now, so decided to add some performance comparison of my own.
I created two arrays containing 1000 dates each. All dates will naturally be different instances (meaning direct === checks will fail), so what this benchmark does, is test what the fastest way is to convert a date to a primitive.
Here's the test data:
const data1 = Array.from({length: 1000}, () => new Date())
const data2 = Array.from({length: 1000}, () => new Date())
And here are the test cases (there's more in the link below):
// 1
data1.forEach((d1, i) => d1.getTime() === data2[i].getTime());
// 2
data1.forEach((d1, i) => d1.valueOf() === data2[i].valueOf());
// 3
data1.forEach((d1, i) => Number(d1) === Number(data2[i]));
// 4
data1.forEach((d1, i) => d1.toISOString() === data2[i].toISOString());
Result (use date.getTime())
Not a surprise that a date.getTime() conversion is much faster. It's around 25% faster than date.valueOf(), and between 10x and 100x faster than everything else (as far as I've checked).
Additionally, introducing optional chaining slowed the best case by almost 10% for me. Found that interesting. date.valueOf() also slowed down by 5% compared to its non optional chaining counterpart.
data1.forEach((d1, i) => d1?.getTime() === data2[i]?.getTime());
Benchmark link: here
Here's an image, in case the above link breaks at some point in the future.
You can also use the function valueOf()
var startDate1 = new Date("02/10/2012").valueOf();
var startDate2 = new Date("01/10/2012").valueOf();
var startDate3 = new Date("01/10/2012").valueOf();
alert(startDate1>startDate2); // 1326150000000 > 1328828400000 true
alert(startDate2==startDate3); // 1328828400000 > 1326150000000 false
One more way of comparing two dates would be converting dates to timestamps using "+" operator before the date.
So, let's say we have two dates:
const dateOne = new Date("10 January 1986")
const dateTwo = new Date("10 December 2020")
if(+dateOne == +dateTwo){
//do something
}
and so on.
This is really handy if you are sorting date objects too as you can use this in the sorting callback function.

javascript getTime() to 10 digits only

I am using the following function to get the Time using javascript:
function timeMil(){
var date = new Date();
var timeMil = date.getTime();
return timeMil;
}
And the value I get is:
1352162391299
While in PHP, I use the time(); function to get Time and the value I get is
1352162391
How do I convert the value of javascript time to remove the last 3 digits and make it 10 digits only.
From 1352162391299 To 1352162391
So that the Javascript time is the same with the PHP time.
I think you just have to divide it by 1000 milliseconds and you'll get time in seconds
Math.floor(date.getTime()/1000)
If brevity is ok, then:
function secondsSinceEpoch() {
return new Date/1000 | 0;
}
Where:
new Date is equivalent to new Date()
| 0 truncates the decimal part of the result and is equivalent to Math.floor(new Date/1000) (see What does |0 do in javascript).
Using newer features, and allowing for a Date to be passed to the function, the code can be reduced to:
let getSecondsSinceEpoch = (x = new Date) => x/1000 | 0;
But I prefer function declarations as I think they're clearer.
Try dividing it by 1000, and use parseInt method.
const t = parseInt(Date.now()/1000);
console.log(t);
function ts() {
return parseInt(Date.now()/1000);
}
You could divide by 1000 and use Math.floor() on JavaScript.

Categories

Resources