简体   繁体   中英

Convert relative time into absolute time with Moment

I have some string in these format:

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

I want to convert these into real and absolute date.

I try to use Moment, with this code example:

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

But it said me that my date is invalid, it does not like my weird date format.

How to process this?

Thank you

I'm not aware of a Moment native solution to your problem, but you can achieve the same result by combining RegExp and Moment's subtract .

Note: The code below is a simple example, and should be extended to other possible inputs.

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

It's a bit verbose, but you get the hang of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM