我有一些這些格式的字串:
"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);
但它說我的日期無效,它不喜歡我奇怪的日期格式。
如何處理這個?
謝謝
uj5u.com熱心網友回復:
我不知道您的問題的 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));
這有點冗長,但你明白了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/414509.html
標籤:
下一篇:為什么“$(where.exegit|select-object-first1)”設定了$LastExitCode?
