使用 Moment 将相对时间转换为绝对时间

Convert relative time into absolute time with Moment

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

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

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

如何处理?

谢谢

我不知道您的问题有 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));

有点冗长,但你掌握了窍门。