Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

javascript - How to know date is today?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...