/**
* Take the difference between the dates and divide by milliseconds per day.
* Round to nearest whole number to deal with DST.
*/
function datediff(first, second) {
return Math.round((second - first) / (1000 * 60 * 60 * 24));
}
/**
* new Date("dateString") is browser-dependent and discouraged, so we'll write
* a simple parse function for U.S. date format (which does no error checking)
*/
function parseDate(str) {
var mdy = str.split('/');
return new Date(mdy[2], mdy[0] - 1, mdy[1]);
}
alert(datediff(parseDate(first.value), parseDate(second.value)));
<script type="text/javascript" src="date.js"></script>
<script type="text/javascript">
var minutes = 1000*60;
var hours = minutes*60;
var days = hours*24;
var foo_date1 = getDateFromFormat("02/10/2009", "M/d/y");
var foo_date2 = getDateFromFormat("02/12/2009", "M/d/y");
var diff_date = Math.round((foo_date2 - foo_date1)/days);
alert("Diff date is: " + diff_date );
</script>
function treatAsUTC(date) {
var result = new Date(date);
result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
return result;
}
function daysBetween(startDate, endDate) {
var millisecondsPerDay = 24 * 60 * 60 * 1000;
return (treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay;
}
alert(daysBetween($('#first').val(), $('#second').val()));
解释
JavaScript日期计算很棘手,因为Date对象在内部以UTC而不是本地时间存储时间。例如,3/10/2013太平洋标准时间12:00 AM (UTC-08:00)存储为3/10/2013上午8:00 UTC, 3/11/2013太平洋夏令时12:00 AM (UTC-07:00)存储为3/11/2013上午7:00 UTC。在这一天,从午夜到午夜,当地时间在UTC只有23小时!
(2013-11-05 00:00:00) - (2013-11-04 10:10:10) < 1 day
例如,我们需要转换第2个日期:
(2013-11-05 00:00:00) - (2013-11-04 00:00:00) = 1 day
该方法可以在两个日期截断轧机:
var date1 = new Date('2013/11/04 00:00:00');
var date2 = new Date('2013/11/04 10:10:10'); //less than 1
var start = Math.floor(date1.getTime() / (3600 * 24 * 1000)); //days as integer from..
var end = Math.floor(date2.getTime() / (3600 * 24 * 1000)); //days as integer from..
var daysDiff = end - start; // exact dates
console.log(daysDiff);
date2 = new Date('2013/11/05 00:00:00'); //1
var start = Math.floor(date1.getTime() / (3600 * 24 * 1000)); //days as integer from..
var end = Math.floor(date2.getTime() / (3600 * 24 * 1000)); //days as integer from..
var daysDiff = end - start; // exact dates
console.log(daysDiff);
var firstDate = Date.UTC(2015,01,2);
var secondDate = Date.UTC(2015,04,22);
var diff = Math.abs((firstDate.valueOf()
- secondDate.valueOf())/(24*60*60*1000));
/*
* Deze functie gebruiken we om het aantal dagen te bereken van een booking.
* */
$scope.berekenDagen = function ()
{
$scope.booking.aantalDagen=0;
/*De loper is gelijk aan de startdag van je reservatie.
* De copy is nodig anders overschijft angular de booking.van.
* */
var loper = angular.copy($scope.booking.van);
/*Zolang de reservatie beschikbaar is, doorloop de weekdagen van je start tot einddatum.*/
while (loper < $scope.booking.tot) {
/*Tel een dag op bij je loper.*/
loper.setDate(loper.getDate() + 1);
$scope.booking.aantalDagen++;
}
/*Start datum telt natuurlijk ook mee*/
$scope.booking.aantalDagen++;
$scope.infomsg +=" aantal dagen: "+$scope.booking.aantalDagen;
};
// Calculate number of days between two unix timestamps
// ------------------------------------------------------------
var daysBetween = function(timeStampA, timeStampB) {
var oneDay = 24 * 60 * 60 * 1000; // hours * minutes * seconds * milliseconds
var firstDate = new Date(timeStampA * 1000);
var secondDate = new Date(timeStampB * 1000);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
return diffDays;
};
var start = new Date('10/3/2015');
var end = new Date('11/2/2015');
var days = (end - start) / 1000 / 60 / 60 / 24;
console.log(days);
// actually its 30 ; but due to daylight savings will show 31.0xxx
// which you need to offset as below
days = days - (end.getTimezoneOffset() - start.getTimezoneOffset()) / (60 * 24);
console.log(days);
var start= $("#firstDate").datepicker("getDate");
var end= $("#SecondDate").datepicker("getDate");
var days = (end- start) / (1000 * 60 * 60 * 24);
alert(Math.round(days));
function timeDifference(date1, date2) {
var oneDay = 24 * 60 * 60; // hours*minutes*seconds
var oneHour = 60 * 60; // minutes*seconds
var oneMinute = 60; // 60 seconds
var firstDate = date1.getTime(); // convert to milliseconds
var secondDate = date2.getTime(); // convert to milliseconds
var seconds = Math.round(Math.abs(firstDate - secondDate) / 1000); //calculate the diffrence in seconds
// the difference object
var difference = {
"days": 0,
"hours": 0,
"minutes": 0,
"seconds": 0,
}
//calculate all the days and substract it from the total
while (seconds >= oneDay) {
difference.days++;
seconds -= oneDay;
}
//calculate all the remaining hours then substract it from the total
while (seconds >= oneHour) {
difference.hours++;
seconds -= oneHour;
}
//calculate all the remaining minutes then substract it from the total
while (seconds >= oneMinute) {
difference.minutes++;
seconds -= oneMinute;
}
//the remaining seconds :
difference.seconds = seconds;
//return the difference object
return difference;
}
console.log(timeDifference(new Date(2017,0,1,0,0,0),new Date()));
javascript:(function() {
var d = new Date(prompt("First Date or leave blank for today?") || Date.now());
prompt("Days Between", Math.round(
Math.abs(
(d.getTime() - new Date(prompt("Date 2")).getTime())
/(24*60*60*1000)
)
));
})();
var firstDate= new Date(firstDate.setHours(0,0,0,0));
var secondDate= new Date(secondDate.setHours(0,0,0,0));
var timeDiff = firstDate.getTime() - secondDate.getTime();
var diffDays =timeDiff / (1000 * 3600 * 24);
function date_units_diff(a, b, unit_amounts) {
var split_to_whole_units = function (milliseconds, unit_amounts) {
// unit_amounts = list/array of amounts of milliseconds in a
// second, seconds in a minute, etc., for example "[1000, 60]".
time_data = [milliseconds];
for (i = 0; i < unit_amounts.length; i++) {
time_data.push(parseInt(time_data[i] / unit_amounts[i]));
time_data[i] = time_data[i] % unit_amounts[i];
}; return time_data.reverse();
}; if (unit_amounts == undefined) {
unit_amounts = [1000, 60, 60, 24];
};
var utc_a = new Date(a.toUTCString());
var utc_b = new Date(b.toUTCString());
var diff = (utc_b - utc_a);
return split_to_whole_units(diff, unit_amounts);
}
// Example of use:
var d = date_units_diff(new Date(2010, 0, 1, 0, 0, 0, 0), new Date()).slice(0,-2);
document.write("In difference: 0 days, 1 hours, 2 minutes.".replace(
/0|1|2/g, function (x) {return String( d[Number(x)] );} ));
var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.
var utc_a = new Date(a.toUTCString());
var utc_b = new Date(b.toUTCString());
var diff = (utc_b - utc_a); // The difference as milliseconds.
const getDaysDiff = (fromTimestamp, toTimestamp) => {
// set timezone offset with utcOffset if needed
let fromDate = moment(fromTimestamp).utcOffset(8);
let toDate = moment(toTimestamp).utcOffset(8);
// get the start moment of the day
fromDate.set({'hour':0, 'minute': 0, 'second': 0, 'millisecond': 0});
toDate.set({'hour':0, 'minute': 0, 'second': 0, 'millisecond': 0});
let diffDays = toDate.diff(fromDate, 'days');
return diffDays;
}
getDaysDiff(1528889400000, 1528944180000)// 1
//use best practices by labeling your constants.
let MS_PER_SEC = 1000
, SEC_PER_HR = 60 * 60
, HR_PER_DAY = 24
, MS_PER_DAY = MS_PER_SEC * SEC_PER_HR * HR_PER_DAY
;
//let's assume we get Date objects as arguments, otherwise return 0.
function dateDiffInDays(date1Time, date2Time) {
if (!date1Time || !date2Time) return 0;
return Math.round((date2Time - date1Time) / MS_PER_DAY);
}
function getUTCTime(dateStr) {
const date = new Date(dateStr);
// If use 'Date.getTime()' it doesn't compute the right amount of days
// if there is a 'day saving time' change between dates
return Date.UTC(date.getFullYear(), date.getMonth(), date.getDate());
}
function calcInputs() {
let date1 = document.getElementById("date1")
, date2 = document.getElementById("date2")
, resultSpan = document.getElementById("result")
;
if (date1.value && date2.value && resultSpan) {
//remove non-date characters
console.log(getUTCTime(date1.value));
let date1Time = getUTCTime(date1.value)
, date2Time = getUTCTime(date2.value)
, result = dateDiffInDays(date1Time, date2Time)
;
resultSpan.innerHTML = result + " days";
}
}
window.onload = function() { calcInputs(); };
//some code examples
console.log(dateDiffInDays(new Date("1/15/2019"), new Date("1/30/2019")));
console.log(dateDiffInDays(new Date("1/15/2019"), new Date("2/30/2019")));
console.log(dateDiffInDays(new Date("1/15/2000"), new Date("1/15/2019")));
const dayNumber = a => Date.UTC(a.getFullYear(), a.getMonth(), a.getDate()) / (24*60*60*1000);
const daysBetween = (a, b) => dayNumber(b) - dayNumber(a);
// Testing it
const start = new Date(1000, 0, 1); // 1 January 1000
const end = new Date(3000, 0, 1); // 1 January 3000
let current = new Date(start);
for (let days = 0; current < end; days++) {
const diff = daysBetween(start, current);
if (diff !== days) throw "test failed";
current.setDate(current.getDate() + 1); // move current date one day forward
}
console.log("tests succeeded");