问题是如何将JavaScript Date格式化为一个字符串,声明时间经过,类似于您在Stack Overflow上看到的时间显示方式。
e.g.
1分钟前 1小时前 1天前 1个月前 一年前
问题是如何将JavaScript Date格式化为一个字符串,声明时间经过,类似于您在Stack Overflow上看到的时间显示方式。
e.g.
1分钟前 1小时前 1天前 1个月前 一年前
当前回答
下面是我所做的(对象返回时间单位及其值):
function timeSince(post_date, reference) { var reference = reference ? new Date(reference) : new Date(), diff = reference - new Date(post_date + ' GMT-0000'), date = new Date(diff), object = { unit: null, value: null }; if (diff < 86400000) { var secs = date.getSeconds(), mins = date.getMinutes(), hours = date.getHours(), array = [ ['second', secs], ['minute', mins], ['hour', hours] ]; } else { var days = date.getDate(), weeks = Math.floor(days / 7), months = date.getMonth(), years = date.getFullYear() - 1970, array = [ ['day', days], ['week', weeks], ['month', months], ['year', years] ]; } for (var i = 0; i < array.length; i++) { array[i][0] += array[i][1] != 1 ? 's' : ''; object.unit = array[i][1] >= 1 ? array[i][0] : object.unit; object.value = array[i][1] >= 1 ? array[i][1] : object.value; } return object; }
其他回答
回复@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++]); } } }
const createdAt = moment(created_at).fromNow()
量身定制的解决方案
const duration = moment.duration(moment().diff(moment(created_at)))
const createdAt = duration.as('week') >= 1
? `${Math.floor(duration.as('week'))} week(s)`
: duration.as('day') >= 1
? `${Math.floor(duration.as('day'))} day(s)`
: duration.as('hour') >= 1
? `${Math.floor(duration.as('hour'))} hour(s)`
: `${Math.floor(duration.as('minute'))} minute(s)`
将上面的函数更改为
function timeSince(date) {
var seconds = Math.floor(((new Date().getTime()/1000) - date)),
interval = Math.floor(seconds / 31536000);
if (interval > 1) return interval + "y";
interval = Math.floor(seconds / 2592000);
if (interval > 1) return interval + "m";
interval = Math.floor(seconds / 86400);
if (interval >= 1) return interval + "d";
interval = Math.floor(seconds / 3600);
if (interval >= 1) return interval + "h";
interval = Math.floor(seconds / 60);
if (interval > 1) return interval + "m ";
return Math.floor(seconds) + "s";
}
否则它会显示“75分钟”(介于1到2小时之间)。它现在还假定输入日期是Unix时间戳。
const timeHandler = (time: any) => {
var a = moment(); //now
var b = moment.utc(time);
const sec = a.diff(b, 'seconds');
const minuts = a.diff(b, 'minutes');
const hours = a.diff(b, 'hours');
const days = a.diff(b, 'days');
const weeks = a.diff(b, 'weeks');
return weeks == 0
? days == 0
? hours == 0
? minuts == 0
? sec >= 0 && `${sec}s ago`
: `${minuts}m ago`
: `${hours}h ago`
: `${days}d ago`
: `${weeks}w ago`;
};
console.log(timeHandler('2022-11-11T12:11:06.6103808'))
以下是对Sky Sander的解决方案的轻微修改,允许日期作为字符串输入,并能够显示像“1分钟”而不是“73秒”这样的跨度
var timeSince = function(date) { if (typeof date !== 'object') { date = new Date(date); } var seconds = Math.floor((new Date() - date) / 1000); var intervalType; var interval = Math.floor(seconds / 31536000); if (interval >= 1) { intervalType = 'year'; } else { interval = Math.floor(seconds / 2592000); if (interval >= 1) { intervalType = 'month'; } else { interval = Math.floor(seconds / 86400); if (interval >= 1) { intervalType = 'day'; } else { interval = Math.floor(seconds / 3600); if (interval >= 1) { intervalType = "hour"; } else { interval = Math.floor(seconds / 60); if (interval >= 1) { intervalType = "minute"; } else { interval = seconds; intervalType = "second"; } } } } } if (interval > 1 || interval === 0) { intervalType += 's'; } return interval + ' ' + intervalType; }; var aDay = 24 * 60 * 60 * 1000; console.log(timeSince(new Date(Date.now() - aDay))); console.log(timeSince(new Date(Date.now() - aDay * 2)));