Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know date is today?

Tags:

I am trying this but is not working... why?

<html> <body>     <script type="text/javascript">          var today=new Date(); //today is Nov 28, 2010         today.setHours(0);         today.setMinutes(0);         today.setSeconds(0);         document.write(today+" ");          var today2 = new Date("November 28, 2010");         document.write(today2 + " ");         if (today == today2) { document.write("==");         if (!(today > today2) && !(today < today2) ) {document.write("==  ");}         if (today > today2) { document.write(">  ");}         if (today >= today2 ){ document.write(">=  ");}         if (today < today2 ) { document.write("<  ");}         if (today <= today2 ){ document.write("<=  ");}      </script> </body> </html> 

And I always get this:

Sun Nov 28 2010 00:00:00 GMT+0900 (JST) Sun Nov 28 2010 00:00:00 GMT+0900 (JST) > >= 

Aren't both dates to be the same? Hence, I should get == printed but is not happening... ;(

Thank you for your help in advance.

like image 484
nacho4d Avatar asked Nov 27 '10 17:11

nacho4d


People also ask

How do I know if a date is today?

To check if a date is 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 I get todays date in JavaScript?

Use new Date() to generate a new Date object containing the current date and time. This will give you today's date in the format of mm/dd/yyyy. Simply change today = mm +'/'+ dd +'/'+ yyyy; to whatever format you wish.

How can you tell if two date objects are on the same day?

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.


2 Answers

They will never match because you're comparing two separate Date object instances.

You need to get some common value that can be compared. For example .toDateString().

today.toDateString() == today2.toDateString();  // true 

If you just compare two separate Date objects, even if they have the exact same date value, they are still different.

For example:

today == new Date( today );  // false 

They are the same date/time value, but are not the same object, so the result is false.

like image 133
user113716 Avatar answered Oct 01 '22 08:10

user113716


function today(td) {     var d = new Date();     return td.getDate() == d.getDate() && td.getMonth() == d.getMonth() && td.getFullYear() == d.getFullYear(); } 
like image 24
user2619282 Avatar answered Oct 01 '22 06:10

user2619282