JavaScript 中日期之间的差异 [英] Difference between dates in JavaScript

查看:28
本文介绍了JavaScript 中日期之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何找出两个日期之间的差异?

How to find the difference between two dates?

推荐答案

通过使用日期 对象和它的毫秒值,可以计算差异:

By using the Date object and its milliseconds value, differences can be calculated:

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 将其转换为秒然后将结果转换为整数(这将删除代表毫秒的小数部分)来获得秒数(作为整数/整数):

You can get the number of seconds (as a integer/whole number) by dividing the milliseconds by 1000 to convert it to seconds then converting the result to an integer (this removes the fractional part representing the milliseconds):

var seconds = parseInt((b-a)/1000);

然后您可以通过将 seconds 除以 60 并将其转换为整数,然后将 hours 除以 minutes 得到整个 minutes 乘以 60 并将其转换为整数,然后以相同的方式转换更长的时间单位.由此,可以创建一个函数,以在下位单位的值和剩余下位单位的值中获取时间单位的最大总量:

You could then get whole minutes by dividing seconds by 60 and converting it to an integer, then hours by dividing minutes by 60 and converting it to an integer, then longer time units in the same way. From this, a function to get the maximum whole amount of a time unit in the value of a lower unit and the remainder lower unit can be created:

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.

如果您想知道上面为第二个日期对象提供的输入参数是什么是,请参阅下面的名称:

If you're wondering what the input parameters provided above for the second Date object are, see their names below:

new Date(<year>, <month>, <day>, <hours>, <minutes>, <seconds>, <milliseconds>);

如本解决方案的评论中所述,您不一定需要提供所有这些值,除非您希望表示的日期需要这些值.

As noted in the comments of this solution, you don't necessarily need to provide all these values unless they're necessary for the date you wish to represent.

这篇关于JavaScript 中日期之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆