【问题标题】:Convert relative time into absolute time with Moment使用 Moment 将相对时间转换为绝对时间
【发布时间】:2022-01-14 14:13:52
【问题描述】:

我有一些这些格式的字符串:

"13 hours and 24 minutes ago"
"12 minutes ago"
"3 seconds ago"

我想将这些转换为真实的绝对日期。

我尝试通过以下代码示例使用 Moment:

var moment = require('moment');

var time = "14 hours and 24 minutes ago";
var formatted = moment(time, "HH hours and mm minutes ago").format("HH:mm:ss");
console.log(formatted);

但它说我的日期无效,它不喜欢我奇怪的日期格式。

如何处理?

谢谢

【问题讨论】:

    标签: node.js date momentjs


    【解决方案1】:

    我不知道 Moment 原生解决方案可以解决您的问题,但您可以通过结合 RegExp 和 Moment 的 subtract 来获得相同的结果。

    注意:下面的代码是一个简单的例子,应该扩展到其他可能的输入。

    /*
    * Works with:
    * "3 second(s) ago"
    * "12 minute(s) ago"
    * "5 hour(s) ago"
    * "13 hour(s) and 24 minute(s) ago"
    */
    const timeString = '1 hour and 15 minutes ago';
    
    function getDateFromTimeAgo(time) {
      const timeAgo = { hours: 0, minutes: 0, seconds: 0 };
    
      const secondsAgoMatches = timeString.match(/^(\d+) (seconds? ago)/);
      const minutesAgoMatches = timeString.match(/^(\d+) (minutes? ago)/);
      const hoursAgoMatches = timeString.match(/^(\d+) (hours? ago)/);
      const hoursAndMinutesAgoMatches = timeString.match(/^(\d+) (hours? and) (\d+) (minutes? ago)/);
    
      if (secondsAgoMatches) {
        timeAgo.seconds = secondsAgoMatches[1];
      }
      if (minutesAgoMatches) {
        timeAgo.minutes = minutesAgoMatches[1];
      }
      if (hoursAgoMatches) {
        timeAgo.hours = hoursAgoMatches[1];
      }
      if (hoursAndMinutesAgoMatches) {
        timeAgo.hours = hoursAndMinutesAgoMatches[1];
        timeAgo.minutes = hoursAndMinutesAgoMatches[3];
      }
    
      return moment()
        .subtract(timeAgo.seconds, 'seconds')
        .subtract(timeAgo.minutes, 'minutes')
        .subtract(timeAgo.hours, 'hours')
        .format();
    }
    
    console.log(getDateFromTimeAgo(timeString));
    

    这有点冗长,但你懂的。

    【讨论】:

    • 我正在做一个类似的代码,太糟糕了,没有原生的方式来用 Moment 做它:) 谢谢
    猜你喜欢
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    • 2015-04-10
    相关资源
    最近更新 更多