English 中文(简体)
如何计算 Java日差? [复制]
原标题:How to calculate date difference in JavaScript? [duplicate]

我想计算日数、小时、分钟、秒、秒、小秒、小秒。 我如何能够这样做?

问题回答

假设你有两个Datebjects,你可以简单地将其细分为零秒:

var difference = date2 - date1;

从那以后,你可以采用简单的算法来得出其他价值。

var DateDiff = {
 
    inDays: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();
 
        return Math.floor((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));

守则样本摘自

另一种解决办法是将差异转化为新的日期目标,并将之年(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天”相同。 如果你想要改变一种能够帮助你们的人类可读风格。

像“白天”这样的表述从来没有像现在这样简单。 如果您有以下日期:

d1: 2011-10-15 23:59:00
d1: 2011-10-16 00:01:00

时间差异为2分钟,“白天”为1或0分钟? 月、年或年、月和日之间任何区别的表述都会产生类似问题,时间长短不一,时间不一(例如,日光储蓄的起步时间比通常短1小时,时间短2小时)。

这里的功能是,在忽略时间的几天内,即在上述日期,可以产生差异。

/*
   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 );
}

这可以更简明扼要:

/*  Return number of days between d0 and d1.
**  Returns positive if d0 < d1, otherwise negative.
**
**  e.g. between 2000-02-28 and 2001-02-28 there are 366 days
**       between 2015-12-28 and 2015-12-29 there is 1 day
**       between 2015-12-28 23:59:59 and 2015-12-29 00:00:01 there is 1 day
**       between 2015-12-28 00:00:01 and 2015-12-28 23:59:59 there are 0 days
**        
**  @param {Date} d0  - start date
**  @param {Date} d1  - end date
**  @returns {number} - whole number of days between d0 and d1
**
*/
function daysDifference(d0, d1) {
  var diff = new Date(+d1).setHours(12) - new Date(+d0).setHours(12);
  return Math.round(diff/8.64e7);
}

// Simple formatter
function formatDate(date){
  return [date.getFullYear(),( 0 +(date.getMonth()+1)).slice(-2),( 0 +date.getDate()).slice(-2)].join( - );
}

// Examples
[[new Date(2000,1,28), new Date(2001,1,28)],  // Leap year
 [new Date(2001,1,28), new Date(2002,1,28)],  // Not leap year
 [new Date(2017,0,1),  new Date(2017,1,1)] 
].forEach(function(dates) {
  document.write( From   + formatDate(dates[0]) +   to   + formatDate(dates[1]) +
                   is   + daysDifference(dates[0],dates[1]) +   days<br> );
});
<html lang="en">
<head>
<script>
function getDateDiff(time1, time2) {
  var str1= time1.split( / );
  var str2= time2.split( / );

  //                yyyy   , mm       , dd
  var t1 = new Date(str1[2], str1[0]-1, str1[1]);
  var t2 = new Date(str2[2], str2[0]-1, str2[1]);

  var diffMS = t1 - t2;    
  console.log(diffMS +   ms );

  var diffS = diffMS / 1000;    
  console.log(diffS +    );

  var diffM = diffS / 60;
  console.log(diffM +   minutes );

  var diffH = diffM / 60;
  console.log(diffH +   hours );

  var diffD = diffH / 24;
  console.log(diffD +   days );
  alert(diffD);
}

//alert(getDateDiff( 10/18/2013 , 10/14/2013 ));
</script>
</head>
<body>
  <input type="button" 
       onclick="getDateDiff( 10/18/2013 , 10/14/2013 )" 
       value="clickHere()" />

</body>
</html>

http://momentjs.com/“rel=“noreferer”_Moment.js 用于所有 Java的同日计算

Answer to your question is:

var a = moment([2007, 0, 29]);   
var b = moment([2007, 0, 28]);    
a.diff(b) // 86400000  

详细情况见

在@paresh mayani的回答中加上“Facebook”等工作,表明在间隔/分钟/小时/周/月/年数上过多少时间

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);

http://momentjs.com/rel=“noreferer” 简单:

moment("2016-04-08").fromNow();
function DateDiff(date1, date2) {
    date1.setHours(0);
    date1.setMinutes(0, 0, 0);
    date2.setHours(0);
    date2.setMinutes(0, 0, 0);
    var datediff = Math.abs(date1.getTime() - date2.getTime()); // difference 
    return parseInt(datediff / (24 * 60 * 60 * 1000), 10); //Convert values days and return value      
}
var d1=new Date(2011,0,1); // jan,1 2011
var d2=new Date(); // now

var diff=d2-d1,sign=diff<0?-1:1,milliseconds,seconds,minutes,hours,days;
diff/=sign; // or diff=Math.abs(diff);
diff=(diff-(milliseconds=diff%1000))/1000;
diff=(diff-(seconds=diff%60))/60;
diff=(diff-(minutes=diff%60))/60;
days=(diff-(hours=diff%24))/24;

console.info(sign===1?"Elapsed: ":"Remains: ",
             days+" days, ",
             hours+" hours, ",
             minutes+" minutes, ",
             seconds+" seconds, ",
             milliseconds+" milliseconds.");

我认为应该这样做。

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))

根据javascript 操作时间原型,你可以使用简单的算法,将时间推到下文。

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);

差异回报的答案是零,然后,你必须按司来转换:

  • by 1000 to convert to second
  • by 1000×60 convert to minute
  • by 1000×60×60 convert to hour
  • by 1000×60×60×24 convert to day
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

Sorry but flat millisecond calculation is not reliable Thanks for all the responses, but few of the functions I tried are failing either on 1. A date near today s date 2. A date in 1970 or 3. A date in a leap year.

最能为我工作并涵盖所有情况的方法,例如,从1970年起的跳跃到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.");

该法典将在以下两个日期之间恢复差异:

const previous_date = new Date("2019-12-23");
const current_date = new Date();

const current_year = current_date.getFullYear();
const previous_date_year = 
previous_date.getFullYear();

const difference_in_years = current_year - 
previous_date_year;

let months = current_date.getMonth();
months = months + 1; // for making the indexing 
// of months from 1

for(let i = 0; i < difference_in_years; i++){
months = months + 12;
}

let days = current_date.getDate();

days = days + (months * 30.417);

console.log(`The days between ${current_date} and 
${previous_date} are : ${days} (approximately)`);

如果你使用时间的话。 j 那么,发现日期差异非常简单。

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")

这就是你如何在没有框架的情况下实现日期之间的区别。

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"));

function daysInMonth (month, year) {
    return new Date(year, month, 0).getDate();
}
function getduration(){

let A= document.getElementById("date1_id").value
let B= document.getElementById("date2_id").value

let C=Number(A.substring(3,5))
let D=Number(B.substring(3,5))
let dif=D-C
let arr=[];
let sum=0;
for (let i=0;i<dif+1;i++){
  sum+=Number(daysInMonth(i+C,2019))
}
let sum_alter=0;
for (let i=0;i<dif;i++){
  sum_alter+=Number(daysInMonth(i+C,2019))
}
let no_of_month=(Number(B.substring(3,5)) - Number(A.substring(3,5)))
let days=[];
if ((Number(B.substring(3,5)) - Number(A.substring(3,5)))>0||Number(B.substring(0,2)) - Number(A.substring(0,2))<0){
days=Number(B.substring(0,2)) - Number(A.substring(0,2)) + sum_alter
}

if ((Number(B.substring(3,5)) == Number(A.substring(3,5)))){
console.log(Number(B.substring(0,2)) - Number(A.substring(0,2)) + sum_alter)
}

time_1=[]; time_2=[]; let hour=[];
 time_1=document.getElementById("time1_id").value
 time_2=document.getElementById("time2_id").value
  if (time_1.substring(0,2)=="12"){
     time_1="00:00:00 PM"
  }
if (time_1.substring(9,11)==time_2.substring(9,11)){
hour=Math.abs(Number(time_2.substring(0,2)) - Number(time_1.substring(0,2)))
}
if (time_1.substring(9,11)!=time_2.substring(9,11)){
hour=Math.abs(Number(time_2.substring(0,2)) - Number(time_1.substring(0,2)))+12
}
let min=Math.abs(Number(time_1.substring(3,5))-Number(time_2.substring(3,5)))
document.getElementById("duration_id").value=days +" days "+ hour+"  hour " + min+"  min " 
}
<input type="text" id="date1_id" placeholder="28/05/2019">
<input type="text" id="date2_id" placeholder="29/06/2019">
<br><br>
<input type="text" id="time1_id" placeholder="08:01:00 AM">
<input type="text" id="time2_id" placeholder="00:00:00 PM">
<br><br>
<button class="text" onClick="getduration()">Submit </button>
<br><br>
<input type="text" id="duration_id" placeholder="days hour min">
var date1 = new Date("06/30/2019");
var date2 = new Date("07/30/2019");
  
// To calculate the time difference of two dates
var Difference_In_Time = date2.getTime() - date1.getTime();
  
// To calculate the no. of days between two dates
var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
  
//To display the final no. of days (result)
document.write("Total number of days between dates  <br>"
               + date1 + "<br> and <br>" 
               + date2 + " is: <br> " 
               + Difference_In_Days);

如果你只需要表明剩下的时间,那就应该做些什么,因为 Java在你身边的时候就使用了框架。 结束时间——我们从表面上1 000个框架到1秒,就可以将其分为1 000个时间段,因为你可以使用基本时间数,但是,由于计算是静态的,它每年可以补偿不同的总天数(360/365/366)。

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;

我在以下职能中做了改动:now <>/strong>和2021-02-26T21:50:42.123>

The difference return answer as milliseconds, so I convert it by using this formula:

<代码>(1000 * 3600 * 24)。

function getDiff(dateAcquired) {
      let calDiff = Math.floor(
        (new Date() - new Date(dateAcquired)) / (1000 * 3600 * 24)
      );
      return calDiff;
    }
    console.log(getDiff("2021-02-26T21:50:42.123"));

Can be useful :

const date_diff = (date1, date2) => Math.ceil(Math.abs(date1 - date2)/24 * 60 * 60 * 1000)

const date_diff = (date1, date2) => Math.ceil(Math.abs(date1 - date2)/86400000)

页: 1

谢谢。

            // the idea is to get time left for new year.
           // Not considering milliseconds as of now, but that 
           //  can be done
           
            var newYear =  1 Jan 2023 ;
            const secondsInAMin = 60;
            const secondsInAnHour = 60 * secondsInAMin;
            const secondsInADay = 24 * secondsInAnHour;

            function DateDiffJs() {
                var newYearDate = new Date(newYear);
                var currDate = new Date();

                var remainingSecondsInDateDiff = (newYearDate - currDate) / 1000;
                var days = Math.floor(remainingSecondsInDateDiff / secondsInADay);

                var remainingSecondsAfterDays = remainingSecondsInDateDiff - (days * secondsInADay);
                var hours = Math.floor(remainingSecondsAfterDays / secondsInAnHour);

                var remainingSecondsAfterhours = remainingSecondsAfterDays - (hours * secondsInAnHour);
                var mins = Math.floor(remainingSecondsAfterhours / secondsInAMin);

                var seconds = Math.floor(remainingSecondsAfterhours - (mins * secondsInAMin));


                console.log(`days :: ${days}`)
                console.log(`hours :: ${hours}`)
                console.log(`mins :: ${mins}`)
                console.log(`seconds :: ${seconds}`)

            }

            DateDiffJs();




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.