简体   繁体   中英

Javascript Date Comparison not behaving as expected

I am getting a SQL date - NOT datetime - object pushed into my Javascript code, and I need to see whether it's before today or not. Here is the code I have (the relevant part):

todaysDate = new Date();
todaysDate.setHours(0,0,0,0);
var date = Date.parse(row[3]);
// date.setHours(0,0,0,0);
if (date < todaysDate) {
    alert("date is before today");
    dueDate = '<small class="text-danger">';
} else {
    alert("date is after today");
    dueDate = '<small class="text-muted">';
}

row[3] is the source of the SQL date. So, this works fine for everything except dates that are today. Without the commented line, it thinks that anything with today's date is in the past. With the commented line, my code breaks. Any thoughts as to how to fix this? Not sure what I'm doing wrong.

Thanks!

If your date string is like "2016-04-10" and your time zone is west of GMT, say -04:00, then in browsers compliant with ECMAScript 2016 you will get a Date for "2016-04-09T19:00:00-0400".

When you create a Date using new Date() and set the hours to zero (assuming it's 10 April where you are), you'll get a Date for "2016-04-10T00:00:00-0400".

So when compared they have different time values.

What you need is to either treat the string you get from the database as local, or get the UCT date where you are, so:

 var dateString = '2016-04-10'; var parsedDate = new Date(dateString); var todayUTCDate = new Date(); todayUTCDate.setUTCHours(0,0,0,0); document.write(parsedDate + '<br>' + todayUTCDate); 

But not all browsers parse strings according to ECMAScript 2015 so they should always be manually parsed. Use a library, or write a small function, eg

// Parse date string in format 'yyyy-mm-dd' as local date
function parseISOLocal(s) {
  var b = s.split(/\D/);
  return new Date(b[0], b[1]-1, b[2]);
}

and replace:

var date = Date.parse(row[3]);

with:

var date = parseISOLocal(row[3]);

and then in the comparison, compare the time values:

if (+date < +todaysDate) {

or

if (date.getTime() < todaysDate.getTime()) {

Use getTime() of date object.

The getTime() method returns the number of milliseconds between midnight of January 1, 1970 and the specified date.

You can compare miliseconds and do your operations

date.getTime() > todaysDate.getTime()

Also be sure that Date.parse is returning a valid date.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM