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

compare two date in javascriptjquery using day accuracy - Stack Overflow

programmeradmin2浏览0评论

I need to pare two dates using best accuracy, for me day will be ok and take into consideration leap years.

It is possible ? I for now only create function to pare month accurancy :/

I need to pare two dates using best accuracy, for me day will be ok and take into consideration leap years.

It is possible ? I for now only create function to pare month accurancy :/

Share Improve this question asked Nov 4, 2012 at 0:21 netmajornetmajor 6,58514 gold badges70 silver badges102 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 2

You can subtract Date object from another Date object and return microseconds

var d= new Date('2012/11/29');
var a= new Date('2012/11/30');
alert( (a-d) /(1000*24*60*60)) ); /* returns 1 */

If you have date strings, you can parse them by using Date.parse("datestring"). It will return long(time in milliseconds). And you can pare any two longs.

var date1 = new Date("10/25/2011");
var date2 = new Date("09/03/2010");
var date3 = new Date(Date.parse(date1) - Date.parse(date2));

var dayDiff = date3.getDate() - 1;
var monthDiff = date3.getMonth();
var yearDiff = date3.getFullYear() - 1970;

Here is jsfiddle to test it.

The best JavaScript Time and Date manipulation library I've e across is Moment.js

Getting the # of days between two dates:

d1 = moment('2012-10-31')
d2 = moment('2012-11-02')
Math.abs(moment.duration(d1-d2, 'ms').days())
// => 2

The default precision is milliseconds.

This should work for difference in days with fairly good precision:

function daysSince( past ) {
  return 0|( new Date().getTime() - past.getTime() ) * 1.16e-8;
}

console.log( daysSince( new Date('10/03/2012') ) ); //=> 31

Edit: Actually, if you only want to know the difference between two dates you can always return a positive number.

function daysBetweenDates( d1,d2 ) {
  return Math.abs( 0|( d1.getTime() - d2.getTime() ) * 1.16e-8 );
}
发布评论

评论列表(0)

  1. 暂无评论