我实现了这个逻辑,我从 Moment.js 得到 2 个日期和时间之间的差异作为秒,我需要将这些秒转换为 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 日将另一个闰秒添加到我们的日历中 - http://en.wikipedia.org/wiki/Leap_second。)
考虑到所有这些,这个答案非常近似,因为它没有考虑月的长度、闰日或闰秒。但是,它是一些东西:
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();
关于javascript - 如何将秒分别转换为年、月、日、小时、分钟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30679279/