I am trying to know if a certain timestamp belongs to today, but I'm getting lost in Javascripts date management.
Is there any way to check if a timestampo belongs to the current day?
26 Answers
Simple check 1st timestamp of both days and compare them.
var ts = 1564398205000 var today = new Date().setHours(0, 0, 0, 0); var thatDay = new Date(ts).setHours(0, 0, 0, 0); if(today === thatDay){ console.log("*** Same day ***"); } It seems nasty-ish to me however you could do something similar to:
function isInToday(inputDate) { var today = new Date(); if(today.setHours(0,0,0,0) == inputDate.setHours(0,0,0,0){ return true; } else { return false; } } This assumes you've already set your input date as a JS date. This will check if the two dates occur on the same day, and return true if so and false if not.
I'm sure someone will come along with a neater way to do this or a case where this fails but as far as I can see this should do the trick for you.
1you can really depend on ISO date string with a substr function to compare the two strings
var T=1479288780873; /*assume your timestamp value*/ var theDay=new Date(T); var today=new Date; theDay.toISOString().substr(0,10) == today.toISOString().substr(0,10) ? console.log("same day"):null; You can do something like this :
var day = 24 * 60 * 60 * 1000; //nb millis in a day var todayTimestamp = new Date(year, month, day).getTime(); // Be careful month is 0 start //OR var todayTimestamp = new Date().setHours(0,0,0,0).getTime(); var diff = myTimestamp - todayTimestamp; if ( diff >= 0 && diff <= day ) { console.log("timestamp is today"); else { console.log("timestamp is not today"); } var timestamp = '2016-11-16 03:14:07.999999'; var datestamp = timestamp.substring(0, 10); Date.prototype.yyyymmdd = function() { var mm = this.getMonth() + 1; var dd = this.getDate(); return [this.getFullYear(), mm, dd].join('-'); }; var date = new Date(); date.yyyymmdd(); console.log(String(datestamp) === String(date.yyyymmdd())); It depends what format your timestamp is in. But here is the most basic way to achieve this:
var today = new Date(year, month, day); var timestamp = //your timestamp; if (timestamp == timestamp){ //make sure the date formats are the same //your code } I hope this is what you were looking for, there are more methods with the javascript date reference, don't hesitate to look it up.