Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 210
Xar Avatar asked Nov 16 '16 09:11

Xar


People also ask

How do you check the input date is equal to today's date or not using JavaScript?

To check if a date is today's date:Use the Date() constructor to get today's date. Use the toDateString() method to compare the two dates. If the method returns 2 equal strings, the date is today's date.

How do you check if the dates are the same day JavaScript?

To check if two dates are the same day, call the toDateString() method on both Date() objects and compare the results. If the output from calling the method is the same, the dates are the same day.

How do you know if a date was yesterday?

To check if a date is yesterday:Subtract 1 day from the current date to get yesterday's date.


2 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 ***");
}
like image 99
Aman Jain Avatar answered Sep 30 '22 17:09

Aman Jain


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.

like image 21
Coombes Avatar answered Sep 30 '22 17:09

Coombes