【问题标题】:How to Convert Seconds into Year, Month, Days, Hours, Minutes respectively?如何将秒分别转换为年、月、日、小时、分钟?
【发布时间】:2015-06-06 05:31:39
【问题描述】:

我实现了这个逻辑,我将 Moment.js 中的 2 个日期和时间之间的差异作为秒数,我需要将这些秒数转换为 1 Year 3 Months 10 Days 5 Hours 45 Minutes 格式。

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);

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

【问题讨论】:

  • 标签太多!!每个环境中 API 的细微差别。具体...
  • Moment 不是已经支持这种提取了吗? (有人性化,我认为可能有办法获得另一种表示或使用现有的大部分内容。)
  • 你可以使用 moment-duration-format 。

标签: javascript


【解决方案1】:

日期和日历是政治性的,并不总是与简单的算术相匹配。我使用过的大多数语言都可以为您解决这个问题,据我所知,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();

【讨论】:

    【解决方案2】:

    function TimeCalculator(seconds) {
      let y = Math.floor(seconds / 31536000);
      let mo = Math.floor((seconds % 31536000) / 2628000);
      let d = Math.floor(((seconds % 31536000) % 2628000) / 86400);
      let h = Math.floor((seconds % (3600 * 24)) / 3600);
      let m = Math.floor((seconds % 3600) / 60);
      let s = Math.floor(seconds % 60);
    
      let yDisplay = y > 0 ? y + (y === 1 ? " year, " : " years, ") : "";
      let moDisplay = mo > 0 ? mo + (mo === 1 ? " month, " : " months, ") : "";
      let dDisplay = d > 0 ? d + (d === 1 ? " day, " : " days, ") : "";
      let hDisplay = h > 0 ? h + (h === 1 ? " hour, " : " hours, ") : "";
      let mDisplay = m > 0 ? m + (m === 1 ? " minute " : " minutes, ") : "";
      let sDisplay = s > 0 ? s + (s === 1 ? " second" : " seconds ") : "";
      return yDisplay + moDisplay + dDisplay + hDisplay + mDisplay + sDisplay;
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-24
      • 2017-11-22
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-17
      • 1970-01-01
      相关资源
      最近更新 更多