问题是如何将JavaScript Date格式化为一个字符串,声明时间经过,类似于您在Stack Overflow上看到的时间显示方式。
e.g.
1分钟前 1小时前 1天前 1个月前 一年前
问题是如何将JavaScript Date格式化为一个字符串,声明时间经过,类似于您在Stack Overflow上看到的时间显示方式。
e.g.
1分钟前 1小时前 1天前 1个月前 一年前
当前回答
可读性强且跨浏览器兼容的代码:
@Travis给出的
var DURATION_IN_SECONDS = { epochs: ['year', 'month', 'day', 'hour', 'minute'], year: 31536000, month: 2592000, day: 86400, hour: 3600, minute: 60 }; function getDuration(seconds) { var epoch, interval; for (var i = 0; i < DURATION_IN_SECONDS.epochs.length; i++) { epoch = DURATION_IN_SECONDS.epochs[i]; interval = Math.floor(seconds / DURATION_IN_SECONDS[epoch]); if (interval >= 1) { return { interval: interval, epoch: epoch }; } } }; function timeSince(date) { var seconds = Math.floor((new Date() - new Date(date)) / 1000); var duration = getDuration(seconds); var suffix = (duration.interval > 1 || duration.interval === 0) ? 's' : ''; return duration.interval + ' ' + duration.epoch + suffix; }; alert(timeSince('2015-09-17T18:53:23'));
其他回答
回复@Stas Parshin的答案,这是最好的答案,代码更少,但它在与typescript一起使用时有bug, Intl的.format函数需要2个输入
number, Units - i.e of type 'RelativeTimeFormatUnit' so if you pass a object key typescript will through error saying unit must be of type RelativeTimeFormatUnit and not of type string, so the work-around for this is to use the type to make another list of same type and rest you can have look at code... Happy coding. console.log(timeAgo('2021-08-09T15:29:01+0000')); function timeAgo(input) { const date = (input instanceof Date) ? input : new Date(input); const formatter = new Intl.RelativeTimeFormat('en'); const ranges = { years: 3600 * 24 * 365, months: 3600 * 24 * 30, weeks: 3600 * 24 * 7, days: 3600 * 24, hours: 3600, minutes: 60, seconds: 1 }; type RelativeTimeFormatUnit = | "year" | "years" | "quarter" | "quarters" | "month" | "months" | "week" | "weeks" | "day" | "days" | "hour" | "hours" | "minute" | "minutes" | "second" | "seconds" ; const units: RelativeTimeFormatUnit[] = ["years", "months", "weeks", "days", "hours", "minutes", "seconds"]; // order matters here. const secondsElapsed = (date.getTime() - Date.now()) / 1000; for (let key in ranges) { let i = 0; if (ranges[key] < Math.abs(secondsElapsed)) { const delta = secondsElapsed / ranges[key]; return formatter.format(Math.round(delta), units[i++]); } } }
由@user1012181提供的ES6版本代码:
const epochs = [
['year', 31536000],
['month', 2592000],
['day', 86400],
['hour', 3600],
['minute', 60],
['second', 1]
];
const getDuration = (timeAgoInSeconds) => {
for (let [name, seconds] of epochs) {
const interval = Math.floor(timeAgoInSeconds / seconds);
if (interval >= 1) {
return {
interval: interval,
epoch: name
};
}
}
};
const timeAgo = (date) => {
const timeAgoInSeconds = Math.floor((new Date() - new Date(date)) / 1000);
const {interval, epoch} = getDuration(timeAgoInSeconds);
const suffix = interval === 1 ? '' : 's';
return `${interval} ${epoch}${suffix} ago`;
};
由@ibe-vanmeenen编辑建议。(谢谢!)
我一直在寻找这个问题的答案,并且几乎实现了其中一个解决方案,但一位同事提醒我检查react-intl库,因为我们已经在使用它了。
所以在解决方案中…在使用react-intl库的情况下,它们有一个<FormattedRelative>组件。
https://github.com/yahoo/react-intl/wiki/Components#formattedrelative
以上答案适用于旧的java脚本。但它在新的EC6 JavaScript或TypeScript上运行得不太好。下面是一个非常简短和简单的函数,用于最新的JavaScript, TypeScript, AngularJs, ReactJs和NodeJs,根据给定的日期和时间返回时间。
public timeAgo(date) {
var seconds = Math.floor((new Date().getTime() - new Date(date).getTime()) / 1000);
var interval = seconds / 31536000;
if (interval > 1) return Math.floor(interval) + " years";
interval = seconds / 2592000;
if (interval > 1) return Math.floor(interval) + " months";
interval = seconds / 86400;
if (interval > 1) return Math.floor(interval) + " days";
interval = seconds / 3600;
if (interval > 1) return Math.floor(interval) + " hours";
interval = seconds / 60;
if (interval > 1) return Math.floor(interval) + " minutes";
return Math.floor(seconds) + " seconds";
}
console.log(timeAgo('2022-08-12 20:50:20'));
// 2 hours ago, as per the given date time string.
I achieve this by following method
timeAgo = (date) => {
var ms = (new Date()).getTime() - date.getTime();
var seconds = Math.floor(ms / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
var months = Math.floor(days / 30);
var years = Math.floor(months / 12);
if (ms === 0) {
return 'Just now';
} if (seconds < 60) {
return seconds + ' seconds Ago';
} if (minutes < 60) {
return minutes + ' minutes Ago';
} if (hours < 24) {
return hours + ' hours Ago';
} if (days < 30) {
return days + ' days Ago';
} if (months < 12) {
return months + ' months Ago';
} else {
return years + ' years Ago';
}
}
console.log(timeAgo(new Date()));
console.log(timeAgo(new Date('Jun 27 2020 10:12:19')));
console.log(timeAgo(new Date('Jun 27 2020 00:12:19')));
console.log(timeAgo(new Date('May 28 2020 13:12:19')));
console.log(timeAgo(new Date('May 28 2017 13:12:19')));