最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Javascript date comparison ignoring timestamp value - Stack Overflow

programmeradmin4浏览0评论

What is the simplest way to pare two dates neglecting the timestamps. I have got two dates firstDate ing from the database (converted into javascript date) and secondDate ing from a date picker input field.
Essentially for my algorithm these two dates are equal as it doesn't take timestamp into consideration but the code won't consider it equal as firstDate has 01:00:00 in it.
How to pletely discard the timestamp for parison?

firstDate:

Tue Mar 24 1992 01:00:00 GMT-0500 (Central Daylight Time)

secondDate:

Tue Mar 24 1992 00:00:00 GMT-0500 (Central Daylight Time)

Code:

   if(firstDate < secondDate) {

        alert("This alert shouldn't pop out as dates are equal");
    }

What is the simplest way to pare two dates neglecting the timestamps. I have got two dates firstDate ing from the database (converted into javascript date) and secondDate ing from a date picker input field.
Essentially for my algorithm these two dates are equal as it doesn't take timestamp into consideration but the code won't consider it equal as firstDate has 01:00:00 in it.
How to pletely discard the timestamp for parison?

firstDate:

Tue Mar 24 1992 01:00:00 GMT-0500 (Central Daylight Time)

secondDate:

Tue Mar 24 1992 00:00:00 GMT-0500 (Central Daylight Time)

Code:

   if(firstDate < secondDate) {

        alert("This alert shouldn't pop out as dates are equal");
    }
Share Improve this question edited Feb 15, 2012 at 20:33 Jim Garrison 86.8k20 gold badges160 silver badges193 bronze badges asked Feb 15, 2012 at 20:07 user1195192user1195192 6993 gold badges11 silver badges19 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 9

You could use toDateString to get rid of the the time, and reassign that to the firstDate and secondDate variables. There might be a better way, but this is what came to mind for me.

firstDate = new Date(firstDate.toDateString());
secondDate = new Date(secondDate.toDateString());
if(firstDate < secondDate){
    alert("This alert shouldn't pop out as dates are equal");
}

Also, you'll want to make sure you're paring the values of the dates, and not checking if they're the same object when you pare if they're equal. So something like.

firstDate.valueOf() == secondDate.valueOf()

You can also check out my JSFiddle example.

Use the Date.setHours(hrs, mins, secs, ms) function with all zero arguments to set the time of day to midnight in both dates (make a copy if you need the date with the time for other purposes).

Derek's answer is correct. An alternative method without creating new date instances is to create RFC3339 date strings.

var firstDateStr = firstDate.toISOString().slice(0, 10);
var secondDateStr = secondDate.toISOString().slice(0, 10);

return (firstDateStr < secondDateStr);
发布评论

评论列表(0)

  1. 暂无评论