JavaScript中的日期差异
通过使用Date对象及其毫秒值,差异可以计算:
var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.
var d = (b-a); // Difference in milliseconds.
可以通过将毫秒1000将其转换得到的秒数(作为一个整数/整数)到秒,然后将结果转换为一个整数(本移除表示毫秒的小数部分):
var seconds = parseInt((b-a)/1000);
然后,您可以通过将seconds
60,并获得全minutes
将其转换为整数,然后hours
将minutes
除以60并将其转换为整数,然后以相同方式将其转换为更长的时间单位。由此看来,一个函数来获取较低单元的值的时间单元的最大全量,剩下的更低的单位可创建:
function get_whole_values(base_value, time_fractions) {
time_data = [base_value];
for (i = 0; i < time_fractions.length; i++) {
time_data.push(parseInt(time_data[i]/time_fractions[i]));
time_data[i] = time_data[i] % time_fractions[i];
}; return time_data;
};
// Input parameters below: base value of 72000 milliseconds, time fractions are
// 1000 (amount of milliseconds in a second) and 60 (amount of seconds in a minute).
console.log(get_whole_values(72000, [1000, 60]));
// -> [0,12,1] # 0 whole milliseconds, 12 whole seconds, 1 whole minute.
如果你想知道上面提供什么样的输入参数第二Date object是,见下他们的名字:
new Date(<year>, <month>, <day>, <hours>, <minutes>, <seconds>, <milliseconds>);
在本解决方案的评论中指出,你不一定需要,除非他们是必要的,你要表示日期提供所有这些值。
// This is for first date
first = new Date(2010, 03, 08, 15, 30, 10); // Get the first date epoch object
document.write((first.getTime())/1000); // get the actual epoch values
second = new Date(2012, 03, 08, 15, 30, 10); // Get the first date epoch object
document.write((second.getTime())/1000); // get the actual epoch values
diff= second - first ;
one_day_epoch = 24*60*60 ; // calculating one epoch
if (diff/ one_day_epoch > 365) // check , is it exceei
{
alert('date is exceeding one year');
}
我发现这和正常工作对我来说:
计算两个已知的日期之间的差异
不幸的是,计算日期间隔,例如两个已知日期之间的日期,星期或月份并不容易,因为您不能只将Date对象添加在一起。为了在任何计算中使用Date对象,我们必须先检索Date的内部毫秒值,该值存储为一个大整数。要做到这一点的函数是Date.getTime()。一旦两个日期都进行了转换,从较早的一个中减去后面的一个将以毫秒为单位返回差值。然后可以通过将该数字除以相应的毫秒数来确定期望的间隔。例如,为了获得用于毫秒的给定数目的天数,我们将通过86400000,毫秒的在一天的数目(1000×60秒×60分钟×24小时)划分:
Date.daysBetween = function(date1, date2) {
//Get 1 day in milliseconds
var one_day=1000*60*60*24;
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = date2_ms - date1_ms;
// Convert back to days and return
return Math.round(difference_ms/one_day);
}
//Set the two dates
var y2k = new Date(2000, 0, 1);
var Jan1st2010 = new Date(y2k.getFullYear() + 10, y2k.getMonth(), y2k.getDate());
var today= new Date();
//displays 726
console.log('Days since '
+ Jan1st2010.toLocaleDateString() + ': '
+ Date.daysBetween(Jan1st2010, today));
的舍入是可选的,取决于你是否想要部分日子。
Date.prototype.addDays = function(days) {
var dat = new Date(this.valueOf())
dat.setDate(dat.getDate() + days);
return dat;
}
function getDates(startDate, stopDate) {
var dateArray = new Array();
var currentDate = startDate;
while (currentDate <= stopDate) {
dateArray.push(currentDate);
currentDate = currentDate.addDays(1);
}
return dateArray;
}
var dateArray = getDates(new Date(), (new Date().addDays(7)));
for (i = 0; i < dateArray.length; i ++) {
// alert (dateArray[i]);
date=('0'+dateArray[i].getDate()).slice(-2);
month=('0' +(dateArray[i].getMonth()+1)).slice(-2);
year=dateArray[i].getFullYear();
alert(date+"-"+month+"-"+year);
}
如果你正在寻找一个差异表示为年,月,日的组合,我建议这个功能:
function interval(date1, date2) {
if (date1 > date2) { // swap
var result = interval(date2, date1);
result.years = -result.years;
result.months = -result.months;
result.days = -result.days;
result.hours = -result.hours;
return result;
}
result = {
years: date2.getYear() - date1.getYear(),
months: date2.getMonth() - date1.getMonth(),
days: date2.getDate() - date1.getDate(),
hours: date2.getHours() - date1.getHours()
};
if (result.hours < 0) {
result.days--;
result.hours += 24;
}
if (result.days < 0) {
result.months--;
// days = days left in date1's month,
// plus days that have passed in date2's month
var copy1 = new Date(date1.getTime());
copy1.setDate(32);
result.days = 32-date1.getDate()-copy1.getDate()+date2.getDate();
}
if (result.months < 0) {
result.years--;
result.months+=12;
}
return result;
}
// Be aware that the month argument is zero-based (January = 0)
var date1 = new Date(2015, 4-1, 6);
var date2 = new Date(2015, 5-1, 9);
document.write(JSON.stringify(interval(date1, date2)));
这个解决方案将以我们自然会做的方式(我认为)来对待闰年(2月29日)和月份长度差异。
因此,例如,2015年2月28日至2015年3月28日的时间间隔将被视为恰好一个月,而不是28天。如果这两天都在2016年,那么差异仍然是一个月,而不是29天。
具有完全相同的月份和日期但不同年份的日期总是会有确切的年数差异。因此,2015-03-01和2016-03-01之间的差异将为1年,而不是1年和1天(因为365天为1年)。
var DateDiff = function(type, start, end) {
let // or var
years = end.getFullYear() - start.getFullYear(),
monthsStart = start.getMonth(),
monthsEnd = end.getMonth()
;
var returns = -1;
switch(type){
case 'm': case 'mm': case 'month': case 'months':
returns = (((years * 12) - (12 - monthsEnd)) + (12 - monthsStart));
break;
case 'y': case 'yy': case 'year': case 'years':
returns = years;
break;
case 'd': case 'dd': case 'day': case 'days':
returns = ((end - start)/(1000 * 60 * 60 * 24));
break;
}
return returns;
}
用法
变种qtMonths = DateDiff的( '毫米',新的日期( '2015-05-05'),新的日期());
var qtYears = DateDiff('yy',new Date('2015-05-05'),new Date());
var qtDays = DateDiff('dd',new Date('2015-05-05'),new Date());
OR
变种qtMonths = DateDiff的( 'M',新的日期( '2015-05-05'),新的日期()); // m || y || d
var qtMonths = DateDiff('month',new Date('2015-05-05'),new Date()); //月||年||日期
var qtMonths = DateDiff('months',new Date('2015-05-05'),new Date()); //月||年||天
...
var DateDiff = function (type, start, end) {
let // or var
years = end.getFullYear() - start.getFullYear(),
monthsStart = start.getMonth(),
monthsEnd = end.getMonth()
;
if(['m', 'mm', 'month', 'months'].includes(type)/*ES6*/)
return (((years * 12) - (12 - monthsEnd)) + (12 - monthsStart));
else if(['y', 'yy', 'year', 'years'].includes(type))
return years;
else if (['d', 'dd', 'day', 'days'].indexOf(type) !== -1/*EARLIER JAVASCRIPT VERSIONS*/)
return ((end - start)/(1000 * 60 * 60 * 24));
else
return -1;
}
[比较两个使用JavaScript日期(的可能的复制https://*.com/questions/492994/compare-two-dates-with-javascript ) – 2017-08-02 14:01:12