Xar
Xar

Reputation: 7910

Javascript: how to check if a timestamp belongs to the current day?

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?

Upvotes: 17

Views: 13358

Answers (6)

Aman Jain
Aman Jain

Reputation: 2582

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 ***");
}

Upvotes: 22

Pranay
Pranay

Reputation: 430

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()));

Upvotes: -1

Fefux
Fefux

Reputation: 974

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");
}

Upvotes: 0

Liang
Liang

Reputation: 515

you 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;

Upvotes: 2

Coombes
Coombes

Reputation: 203

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.

Upvotes: 8

Andre Debuisne
Andre Debuisne

Reputation: 303

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.

Upvotes: -4

Related Questions