如何在JavaScript中计算日期差?

如何在JavaScript中计算日期差?,javascript,datetime,Javascript,Datetime,我想用天、小时、分钟、秒、毫秒、纳秒来计算日期差。我该怎么做呢?假设你有两个s,你只需减去它们就可以得到毫秒的差值: var difference = date2 - date1; 从这里,您可以使用简单的算术推导出其他值。var DateDiff={ var DateDiff = { inDays: function(d1, d2) { var t2 = d2.getTime(); var t1 = d1.getTime(); re

我想用天、小时、分钟、秒、毫秒、纳秒来计算日期差。我该怎么做呢?

假设你有两个s,你只需减去它们就可以得到毫秒的差值:

var difference = date2 - date1;
从这里,您可以使用简单的算术推导出其他值。

var DateDiff={
var DateDiff = {

    inDays: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/(24*3600*1000));
    },

    inWeeks: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/(24*3600*1000*7));
    },

    inMonths: function(d1, d2) {
        var d1Y = d1.getFullYear();
        var d2Y = d2.getFullYear();
        var d1M = d1.getMonth();
        var d2M = d2.getMonth();

        return (d2M+12*d2Y)-(d1M+12*d1Y);
    },

    inYears: function(d1, d2) {
        return d2.getFullYear()-d1.getFullYear();
    }
}

var dString = "May, 20, 1984";

var d1 = new Date(dString);
var d2 = new Date();

document.write("<br />Number of <b>days</b> since "+dString+": "+DateDiff.inDays(d1, d2));
document.write("<br />Number of <b>weeks</b> since "+dString+": "+DateDiff.inWeeks(d1, d2));
document.write("<br />Number of <b>months</b> since "+dString+": "+DateDiff.inMonths(d1, d2));
document.write("<br />Number of <b>years</b> since "+dString+": "+DateDiff.inYears(d1, d2));
inDays:功能(d1、d2){ var t2=d2.getTime(); var t1=d1.getTime(); 返回parseInt((t2-t1)/(24*3600*1000)); }, 周内:功能(d1、d2){ var t2=d2.getTime(); var t1=d1.getTime(); 返回parseInt((t2-t1)/(24*3600*1000*7)); }, 月份:功能(d1、d2){ 变量d1Y=d1.getFullYear(); var d2Y=d2.getFullYear(); var d1M=d1.getMonth(); var d2M=d2.getMonth(); 返回(d2M+12*d2Y)-(d1M+12*d1Y); }, 年份:功能(d1、d2){ 返回d2.getFullYear()-d1.getFullYear(); } } var dString=“1984年5月20日”; var d1=新日期(dString); var d2=新日期(); 文件。写入(“
自“+dString+”起的天数:”+DateDiff.inDays(d1,d2)); 文件。写入(“
自“+dString+”起的周数:”+DateDiff.inWeeks(d1,d2)); 文件。写入(“
自“+dString+”起的月数:”+DateDiff.inMonths(d1,d2)); 文件。填写(“
自“+dString+”起的年数:”+DateDiff.inYears(d1,d2));
代码示例取自。

表达式,如“天数差异”从来不像看上去那么简单。如果您有以下日期:

d1: 2011-10-15 23:59:00
d1: 2011-10-16 00:01:00
时间差是2分钟,“天数差”是1还是0?由于年、月和日具有不同的长度和时间(例如,夏令时开始的时间比平时短1小时,结束的时间短2小时),因此,以月、年或其他形式表示的差异也会产生类似的问题

这是一个忽略时间的天数差函数,即对于上述日期,它返回1

/*
   Get the number of days between two dates - not inclusive.

   "between" does not include the start date, so days
   between Thursday and Friday is one, Thursday to Saturday
   is two, and so on. Between Friday and the following Friday is 7.

   e.g. getDaysBetweenDates( 22-Jul-2011, 29-jul-2011) => 7.

   If want inclusive dates (e.g. leave from 1/1/2011 to 30/1/2011),
   use date prior to start date (i.e. 31/12/2010 to 30/1/2011).

   Only calculates whole days.

   Assumes d0 <= d1
*/
function getDaysBetweenDates(d0, d1) {

  var msPerDay = 8.64e7;

  // Copy dates so don't mess them up
  var x0 = new Date(d0);
  var x1 = new Date(d1);

  // Set to noon - avoid DST errors
  x0.setHours(12,0,0);
  x1.setHours(12,0,0);

  // Round to remove daylight saving errors
  return Math.round( (x1 - x0) / msPerDay );
}
/*
获取两个日期之间的天数-不包括在内。
“介于”不包括开始日期,因此
星期四和星期五之间是一天,星期四到星期六
是两个,依此类推。从星期五到下一个星期五是7点。
e、 g.日期之间的GetDays(2011年7月22日、2011年7月29日)=>7。
如果需要包括在内的日期(例如,从2011年1月1日到2011年1月30日休假),
使用开始日期之前的日期(即2010年12月31日至2011年1月30日)。
只算一整天。
假设d0
var d1=新日期(2011,0,1);//2011年1月1日
var d2=新日期();//现在
var diff=d2-d1,符号=diff

函数getDateDiff(time1,time2){
var str1=time1.split('/');
var str2=time2.split('/');
//年月日
变量t1=新日期(str1[2],str1[0]-1,str1[1]);
var t2=新日期(str2[2],str2[0]-1,str2[1]);
var-diffMS=t1-t2;
console.log(diffMS+'ms');
var diffS=diffMS/1000;
控制台日志(差异+“”);
var diffM=diffS/60;
console.log(diffM+分钟);
var diffH=diffM/60;
console.log(diffH+'hours');
var diffD=diffH/24;
console.log(diffD+'days');
警报(diffD);
}
//警报(getDateDiff(“2013年10月18日”、“2013年10月14日”);

另一种解决方案是将差异转换为新的日期对象,并获取该日期的年(与1970年不同)、月、日等

var date1 = new Date(2010, 6, 17);
var date2 = new Date(2013, 12, 18);
var diff = new Date(date2.getTime() - date1.getTime());
// diff is: Thu Jul 05 1973 04:00:00 GMT+0300 (EEST)

console.log(diff.getUTCFullYear() - 1970); // Gives difference as year
// 3

console.log(diff.getUTCMonth()); // Gives month count of difference
// 6

console.log(diff.getUTCDate() - 1); // Gives day count of difference
// 4

所以差别就像“3年6个月4天”。如果您想以一种人类可读的风格来看待差异,这会对您有所帮助。

如果您使用的是moment.js,那么查找日期差异就非常简单了

var now  = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";

moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
用于所有与JavaScript相关的日期时间计算

你的问题的答案是:

var a = moment([2007, 0, 29]);   
var b = moment([2007, 0, 28]);    
a.diff(b) // 86400000  
可以找到完整的详细信息,方法很简单:

moment("2016-04-08").fromNow();

抱歉,平面毫秒计算不可靠 感谢所有的回复,但是我尝试的功能中很少有在这两个方面失败的 1.接近今天的日期 2.1970年或2000年的日期 3.闰年中的日期

最适合我的方法,涵盖所有场景,如闰年、1970年临近日期、2月29日等

var someday = new Date("8/1/1985");
var today = new Date();
var years = today.getFullYear() - someday.getFullYear();

// Reset someday to the current year.
someday.setFullYear(today.getFullYear());

// Depending on when that day falls for this year, subtract 1.
if (today < someday)
{
    years--;
}
document.write("Its been " + years + " full years.");
var=新日期(“1985年8月1日”);
var today=新日期();
var years=today.getFullYear()-某天.getFullYear();
//将某一天重置为当前年份。
某天.setFullYear(今天.getFullYear());
//根据今年该日的时间,减去1。
如果(今天<某一天)
{
年--;
}
文件。写下(“它已经”+年数+“完整年数”);
函数DateDiff(b,e)
{
让
endYear=e.getFullYear(),
endMonth=e.getMonth(),
年份=结束年份-b.getFullYear(),
月数=月末-b.getMonth(),
天=e.getDate()-b.getDate();
如果(月数<0)
{
年--;
月数+=12;
}
如果(天数<0)
{
月--;
天数+=新日期(年底、月末、0)。getDate();
}
返回[年、月、日];
}
[年、月、日]=DateDiff(
新日期(“1980年10月21日”),
新日期(“2017年7月11日”);//36 8 20

这就是在没有框架的情况下实现日期差异的方法

function getDateDiff(dateOne, dateTwo) {
        if(dateOne.charAt(2)=='-' & dateTwo.charAt(2)=='-'){
            dateOne = new Date(formatDate(dateOne));
            dateTwo = new Date(formatDate(dateTwo));
        }
        else{
            dateOne = new Date(dateOne);
            dateTwo = new Date(dateTwo);            
        }
        let timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
        let diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
        let diffMonths = Math.ceil(diffDays/31);
        let diffYears = Math.ceil(diffMonths/12);

        let message = "Difference in Days: " + diffDays + " " +
                      "Difference in Months: " + diffMonths+ " " + 
                      "Difference in Years: " + diffYears;
        return message;
     }

    function formatDate(date) {
         return date.split('-').reverse().join('-');
    }

    console.log(getDateDiff("23-04-2017", "23-04-2018"));

我想这应该可以

let today = new Date();
let form_date=new Date('2019-10-23')
let difference=form_date>today ? form_date-today : today-form_date
let diff_days=Math.floor(difference/(1000*3600*24))
功能日月(月,年){
返回新日期(年、月、0)。getDate();
}
函数getduration(){
设A=document.getElementById(“date1_id”).value
设B=document.getElementById(“date2_id”).value
设C=数(A.子串(3,5))
设D=数(B.子串(3,5))
设dif=D-C
设arr=[];
设和=0;

对于(让i=0;i如果您只需要显示剩余的时间,这应该可以正常工作,因为JavaScript使用帧作为其时间,您将获得结束时间-之后的时间RN,我们可以将其除以1000,因为显然1000帧=1秒,之后您可以使用时间的基本数学,但是这段代码仍然有一个问题,因为计算假设是静态的,它不能补偿一年中不同的总天数(360/365/366),如果时间小于0,则计算后的一组IF将使其为空
var someday = new Date("8/1/1985");
var today = new Date();
var years = today.getFullYear() - someday.getFullYear();

// Reset someday to the current year.
someday.setFullYear(today.getFullYear());

// Depending on when that day falls for this year, subtract 1.
if (today < someday)
{
    years--;
}
document.write("Its been " + years + " full years.");
function DateDiff(b, e)
{
    let
        endYear = e.getFullYear(),
        endMonth = e.getMonth(),
        years = endYear - b.getFullYear(),
        months = endMonth - b.getMonth(),
        days = e.getDate() - b.getDate();
    if (months < 0)
    {
        years--;
        months += 12;
    }
    if (days < 0)
    {
        months--;
        days += new Date(endYear, endMonth, 0).getDate();
    }
    return [years, months, days];
}

[years, months, days] = DateDiff(
    new Date("October 21, 1980"),
    new Date("July 11, 2017")); // 36 8 20
function getDateDiff(dateOne, dateTwo) {
        if(dateOne.charAt(2)=='-' & dateTwo.charAt(2)=='-'){
            dateOne = new Date(formatDate(dateOne));
            dateTwo = new Date(formatDate(dateTwo));
        }
        else{
            dateOne = new Date(dateOne);
            dateTwo = new Date(dateTwo);            
        }
        let timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
        let diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
        let diffMonths = Math.ceil(diffDays/31);
        let diffYears = Math.ceil(diffMonths/12);

        let message = "Difference in Days: " + diffDays + " " +
                      "Difference in Months: " + diffMonths+ " " + 
                      "Difference in Years: " + diffYears;
        return message;
     }

    function formatDate(date) {
         return date.split('-').reverse().join('-');
    }

    console.log(getDateDiff("23-04-2017", "23-04-2018"));
let today = new Date();
let form_date=new Date('2019-10-23')
let difference=form_date>today ? form_date-today : today-form_date
let diff_days=Math.floor(difference/(1000*3600*24))
var now = new Date();
var end = new Date("End Time");
var total = (end - now) ;
var totalD =  Math.abs(Math.floor(total/1000));

var years = Math.floor(totalD / (365*60*60*24));
var months = Math.floor((totalD - years*365*60*60*24) / (30*60*60*24));
var days = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24)/ (60*60*24));
var hours = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24)/ (60*60));
var minutes = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24 - hours*60*60)/ (60));
var seconds = Math.floor(totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24 - hours*60*60 - minutes*60);

var Y = years < 1 ? "" : years + " Years ";
var M = months < 1 ? "" : months + " Months ";
var D = days < 1 ? "" : days + " Days ";
var H = hours < 1 ? "" : hours + " Hours ";
var I = minutes < 1 ? "" : minutes + " Minutes ";
var S = seconds < 1 ? "" : seconds + " Seconds ";
var A = years == 0 && months == 0 && days == 0 && hours == 0 && minutes == 0 && seconds == 0 ? "Sending" : " Remaining";

document.getElementById('txt').innerHTML = Y + M + D + H + I + S + A;
let dt1 = new Date()
let dt2 = new Date()
dt1.setMinutes(7)
dt2.setMinutes(42)
console.log('Elapsed seconds:',(dt2-dt1)/1000)
var dt1 = LocalDateTime.parse("2016-02-26T23:55:42.123");
var dt2 = dt1
  .plusYears(6)
  .plusMonths(12)
  .plusHours(2)
  .plusMinutes(42)
  .plusSeconds(12);

// obtain the duration between the two dates
dt1.until(dt2, ChronoUnit.YEARS); // 7
dt1.until(dt2, ChronoUnit.MONTHS); // 84
dt1.until(dt2, ChronoUnit.WEEKS); // 356
dt1.until(dt2, ChronoUnit.DAYS); // 2557
dt1.until(dt2, ChronoUnit.HOURS); // 61370
dt1.until(dt2, ChronoUnit.MINUTES); // 3682242
dt1.until(dt2, ChronoUnit.SECONDS); // 220934532
var sep = new Date(2020, 07, 31, 23, 59, 59);
var today = new Date();
var diffD = Math.floor((sep - today) / (1000 * 60 * 60 * 24));
console.log('Day Diff: '+diffD);
var DateDiff = {

  inSeconds: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/1000);
    },


  inMinutes: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/60000);
    },

  inHours: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/3600000);
    },

    inDays: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/(24*3600*1000));
    },

    inWeeks: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/(24*3600*1000*7));
    },

    inMonths: function(d1, d2) {
        var d1Y = d1.getFullYear();
        var d2Y = d2.getFullYear();
        var d1M = d1.getMonth();
        var d2M = d2.getMonth();

        return (d2M+12*d2Y)-(d1M+12*d1Y);
    },

    inYears: function(d1, d2) {
        return d2.getFullYear()-d1.getFullYear();
    }
}







    var dString = "May, 20, 1984"; //will also get (Y-m-d H:i:s)
    
    var d1 = new Date(dString);
    var d2 = new Date();
    
    var timeLaps = DateDiff.inSeconds(d1, d2);
    var dateOutput = "";
    
    
    if (timeLaps<60)
    {
      dateOutput = timeLaps+" seconds";
    }
    else  
    {
      timeLaps = DateDiff.inMinutes(d1, d2);
      if (timeLaps<60)
      {
        dateOutput = timeLaps+" minutes";
      }
      else
      {
        timeLaps = DateDiff.inHours(d1, d2);
        if (timeLaps<24)
        {
          dateOutput = timeLaps+" hours";
        }
        else
        {
            timeLaps = DateDiff.inDays(d1, d2);
            if (timeLaps<7)
            {
              dateOutput = timeLaps+" days";
            }
            else
            {
                timeLaps = DateDiff.inWeeks(d1, d2);
                if (timeLaps<4)
                {
                  dateOutput = timeLaps+" weeks";
                }
                else
                {
                    timeLaps = DateDiff.inMonths(d1, d2);
                    if (timeLaps<12)
                    {
                      dateOutput = timeLaps+" months";
                    }
                    else
                    {
                      timeLaps = DateDiff.inYears(d1, d2);
                      dateOutput = timeLaps+" years";
                    }
                }
            }
        }
      }
    }
    
    alert (dateOutput);