在JavaScript日期之间的差异
-
21-09-2019 - |
题
如何找到两个日期之间的区别?
解决方案
通过使用日期对象及其毫秒值,差异可以计算:
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);
您然后可以通过将minutes
由60和60它通过划分seconds
转换为一个整数,那么hours
并将其转换成一个整数以相同的方式,那么较长的时间单位获得整个minutes
。由此看来,一个函数来获取在下部单元的值和下单元可以被创建的其余部分上的时间单元的最大总量:
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.
如果你想知道什么上面对于第二提供的输入参数日期对象是,请参阅下面它们的名称:
new Date(<year>, <month>, <day>, <hours>, <minutes>, <seconds>, <milliseconds>);
在本解决方案的评论中指出,你不一定需要提供所有这些值,除非他们必要让你想表示日期。
其他提示
我发现这和正常工作对我来说:
<强>计算两者之间的差异的已知日期强>
不幸的是,计算日期间隔,例如两个已知的日期之间的天,周或月是不容易,因为你不能只是添加日期对象在一起。为了在任何类型的计算使用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));
舍入是可选的,取决于是否希望局部天或不
// 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');
}
如果您正在寻找表示为年,月和日的组合不同,我建议这个功能:
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)));
此解决方案将处理闰年(29月)和月的长度差的方式,我们自然会做(我认为)。
因此,例如,间隔2月28日和2015年3月之间的2015年28日将被视为整整一个月,而不是28天。如果这两个日子是在2016年,差异依然会整整一个月,而不是29天。
具有完全相同的月份和日期,但不同的年份日期,总会有多年的确切数量的差异。因此,2015年3月1日和2016年3月1日之间的差异将是正好1年,没有1年零1天(因为计算365天为1年)。
此答案,是根据另一个(在端部链节),大约是两个日期之间的差。结果 你可以看到它是如何工作的,因为它的简单,它也包括分裂差转换成结果 的时间(一个函数,我制造),并转换到UTC到停止时区问题的单元。
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.
然后制定出的秒数在于差,除以1000它来转换结果
毫秒到秒,那么结果变为一个整数(整数),以除去结果
毫秒(即小数的小数部分):var seconds = parseInt(diff/1000)
结果
另外,我可以使用相同的过程,例如获得更长的时间单位:点击
- (全)分的,分割的秒 60并将结果改变为一个整数,结果
- 小时,分割的分钟 60并将结果改变为整数
我创建了一个功能,用于做分裂该进程的差转换成搜索
的整个时间单位,命名split_to_whole_units
,与此演示:
console.log(split_to_whole_units(72000, [1000, 60]));
// -> [1,12,0] # 1 (whole) minute, 12 seconds, 0 milliseconds.
此答案基于此另一个。
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 );
}
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'),新的日期());
变种qtYears = DateDiff的( 'YY',新的日期( '2015-05-05'),新的日期());
变种qtDays = DateDiff的( 'DD',新的日期( '2015-05-05'),新的日期());
OR
变种qtMonths = DateDiff的( 'M',新的日期( '2015-05-05'),新的日期()); //米|| ÿ|| d
变种qtMonths = DateDiff的( '月',新的日期( '2015-05-05'),新的日期()); //月||今年||天
变种qtMonths = DateDiff的( '月',新的日期( '2015-05-05'),新的日期()); //月||年||天
...
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;
}