开发者

Javascript calculate difference between two dates yy-mm-dd

开发者 https://www.devze.com 2023-04-11 05:32 出处:网络
I\'ve read quite a few articles and questions on calculating date differences in javascript, but I can\'t find them for the format I\'m looking for.

I've read quite a few articles and questions on calculating date differences in javascript, but I can't find them for the format I'm looking for.

I don't need hours, minutes or believe it or not milliseconds... I just need days. I'm checking to be sure one day occurs on the same day or after another.

Date format is 2010-10-05

I tried this, but all I get is N开发者_如何学JAVAaN:

var diff =  Math.floor(( Date.parse(end_date) - Date.parse(start_date) ) / 86400000);


Do I understand correctly that you don't actually need to know how many days apart the two days are, you just need to know if they're the same date vs. if one is a later date? In that case, regular string comparisons can tell you that, provided you consistently use the format 'yyyy-mm-dd', with two-digit months and two-digit days; for example, '2010-10-05' < '2010-10-16'.


Works fine in Firefox:

JSFiddle

var diff,
  aDay = 86400000,
  start_date = "2010-10-05",
  end_date = "2010-10-15";

diff = Math.floor(
  (
    Date.parse(end_date) - Date.parse(start_date)
  ) / aDay);

console.log(diff)

//but perhaps this is safer:

diff = Math.floor(
  (
    Date.parse(
      end_date.replace(/-/g, '\/')
    ) - Date.parse(
      start_date.replace(/-/g, '\/')
    )
  ) / aDay);
console.log(diff)


You first have to parse the date. However built in Date.parse might not recognize it. Start with the following:

var dateStr = "2010-10-05";
var regex = /(\d{4})-(\d{2})-(\d{2})/.exec(dateStr);
var date = new Date(regex[1], regex[2] - 1, regex[3]);  //Tue Oct 05 2010 00:00:00 GMT+0200 (CEST)

Having two instances of Date objects you can compare them anyway you like. However your condition checks whether two dates are within 24 hours, I guess this is not what you want since your dates do not have timestamps...


I hope this would help you

    t1="2010-12-20";  //date1
    t2="2010-12-30";  //date2

    var one_day=1000*60*60*24; 

    var x=t1.split("-");     
    var y=t2.split("-");

    var date1=new Date(x[0],(x[1]-1),x[2]);
    var date2=new Date(y[0],(y[1]-1),y[2]);

    var month1=x[1]-1;
    var month2=y[1]-1;

    _Diff=Math.ceil((date2.getTime()-date1.getTime())/(one_day));

alert(_Diff);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号