我想用天、小时、分钟、秒、毫秒、纳秒来计算日期差异。我该怎么做呢?
当前回答
像“差几天”这样的表达从来不像看起来那么简单。如果你有以下日期:
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 );
}
这可以更简洁:
/* 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>'); });
其他回答
像“差几天”这样的表达从来不像看起来那么简单。如果你有以下日期:
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 );
}
这可以更简洁:
/* 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>'); });
有很多方法可以做到这一点。 是的,你可以使用普通的旧JS。试试:
let dt1 = new Date()
let dt2 = new Date()
让我们使用Date.prototype.setMinutes模拟通道,并确保我们在范围内。
dt1.setMinutes(7)
dt2.setMinutes(42)
console.log('Elapsed seconds:',(dt2-dt1)/1000)
或者你也可以使用一些像js-joda这样的库,在那里你可以很容易地做这样的事情(直接从文档中):
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
有更多的ofc库,但js-joda还有一个额外的好处,它也可以在Java中使用,在Java中已经进行了广泛的测试。所有这些测试都已迁移到js-joda,它也是不可变的。
使用momentjs很简单:
moment("2016-04-08").fromNow();
// 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();
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">