I am getting some data from SQL which has timestamp and i Wanna check whether they are same day or not....
In a loop i am trying to check the previous loop timestamp is same as the current loop timestamp...... I am trying something like this.....
$.each(data, function(key, value) {
if( new Date([value.startTime] * 1000) === previousdate){
console.log("*** Same day ***");
}
previousdate = new Date([value.startTime] * 1000);
}
But though they are same day but they differ in time ...... I just want to check they both are same day or not..... I can trim them before comparing them so that way it works fine.... but is there any other effective way to do this.....
Cheers...
You can also try checking their date strings.
var isSameDay = function(date, otherDate) {
return date.toDateString() === otherDate.toDateString();
};
This is nice because it's pretty easy to do inline.
It's not clear to me if you want to check if it's the same day or the same date: you talk about same day but from what you're doing seems your want to check if it's the same date. A way to check if it's the same date, is the follow:
$.each(data, function(key, value) {
var current = new Date(value.startTime * 1000).setHours(0, 0, 0, 0);
var previous = new Date(previousDate).setHours(0, 0, 0, 0);
if(current === previous){
console.log("*** Same day ***");
}
previousdate = new Date([value.startTime] * 1000);
})
You basically create a new Date object, resetting all the time values (hours, minutes, seconds, and milliseconds).
If you're using the previousdate
only for this checking, you can simplify:
$.each(data, function(key, value) {
var current = new Date(value.startTime * 1000).setHours(0, 0, 0, 0);
if(current === previousdate){
console.log("*** Same day ***");
}
previousdate = current;
});
Besides the * 1000
operation, that is the easiest and safest way AFAIK. You let the engine doing all the calculation: not all days are made by 24 hours – see the daylight saving time – and not all the minutes are made by 60 seconds – see the leap second; so it's no safe make any operation assuming that.
Of course some engine could not deals with leap second as well, for instance, but it's still better, at least for the daylight saving time.
Since you only care about the UTC date, this should be easy. You timestamp is in number of seconds, so if you divide by the number of seconds in a day and then floor the value, you should get the number of days since Jan 1, 1970. If both values are the same number of days since 1970, then you have a match.
$.each(data, function(key, value) {
var date, previous;
date = Math.floor(value.startTime / 60 / 60 / 24);
if (date === previous){
console.log("*** Same day ***");
}
previous = date;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With