Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/386.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将秒分别转换为年、月、日、小时、分钟?_Javascript - Fatal编程技术网

Javascript 如何将秒分别转换为年、月、日、小时、分钟?

Javascript 如何将秒分别转换为年、月、日、小时、分钟?,javascript,Javascript,我实现了这个逻辑,从Moment.js中得到两个日期和时间之间的差作为秒,我需要将这些秒转换为1年3个月10天5小时45分钟格式 var numyears = Math.floor(seconds / 31536000); var nummonths = Math.floor((seconds % 31536000) / 2628000); var numdays = Math.floor(((seconds % 31536000) % 2628000) / 86400); var numhou

我实现了这个逻辑,从Moment.js中得到两个日期和时间之间的差作为秒,我需要将这些秒转换为
1年3个月10天5小时45分钟
格式

var numyears = Math.floor(seconds / 31536000);
var nummonths = Math.floor((seconds % 31536000) / 2628000);
var numdays = Math.floor(((seconds % 31536000) % 2628000) / 86400);
var numhours = Math.floor((((seconds % 31536000) % 2628000) % 86400)/3600);
var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60);

我得到的是天的正确值,但从小时开始就有问题。

日期和日历是政治性的,并且不总是与简单的算术匹配。我使用过的大多数语言都可以为您解决这个问题,据我所知,JavaScript可以做到这一点。(请注意,我们将在2015年6月30日的日历上再增加一个闰秒。)

考虑到所有这些,这个答案在很大程度上是一个近似值,因为它没有考虑月、闰日或闰秒的长度。但是,它是:

var x = new Date('2015-02-26 12:32:54-0600'); // or if you have milliseconds, use that instead
var y = new Date('2015-03-19 01:22:09-0600');
var z = new Date(y-z);
z;
// returns "Wed Jan 21 1970 06:49:15 GMT-0600 (CST)"
// now compare this with epoch
var epoch = new Date('1970-01-01 00:00:00-0600');
var diff_years = z.getYear() - epoch.getYear();
var diff_month = z.getMonth() - epoch.getMonth();
var diff_days = z.getDate() - epoch.getDate();
var diff_hours = z.getHours() - epoch.getHours();
var diff_minutes = z.getMinutes() - epoch.getMinutes();

标签太多了!!每个环境中API的细微差别。具体一点……难道现在还没有对这个提取的支持吗?(有人性化,我认为可能有一种方法,要么获得另一种表现,要么使用现有的大部分。)你可以使用瞬间持续时间格式。