问题是如何将JavaScript Date格式化为一个字符串,声明时间经过,类似于您在Stack Overflow上看到的时间显示方式。
e.g.
1分钟前 1小时前 1天前 1个月前 一年前
问题是如何将JavaScript Date格式化为一个字符串,声明时间经过,类似于您在Stack Overflow上看到的时间显示方式。
e.g.
1分钟前 1小时前 1天前 1个月前 一年前
当前回答
这是对国际的另一种看法。RelativeTimeFormat
支持过去日期和将来日期 同时接受字符串和日期 易于添加自定义范围(编辑范围) 可以很容易地翻译为Intl.RelativeTimeFormat('ua')
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 }; const secondsElapsed = (date.getTime() - Date.now()) / 1000; for (let key in ranges) { if (ranges[key] < Math.abs(secondsElapsed)) { const delta = secondsElapsed / ranges[key]; return formatter.format(Math.round(delta), key); } } }
https://jsfiddle.net/tv9701uf
其他回答
由@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编辑建议。(谢谢!)
回答10年的老问题,帮助新人。
我们可以将这个包用于javascript时间之前
// Load locale-specific relative date/time formatting rules.
import en from 'javascript-time-ago/locale/en'
// Add locale-specific relative date/time formatting rules.
TimeAgo.addLocale(en)
// Create relative date/time formatter.
const timeAgo = new TimeAgo('en-US')
timeAgo.format(new Date())
// "just now"
timeAgo.format(Date.now() - 60 * 1000)
// "a minute ago"
timeAgo.format(Date.now() - 2 * 60 * 60 * 1000)
// "2 hours ago"
timeAgo.format(Date.now() - 24 * 60 * 60 * 1000)
// "a day ago"
function calDateAgo(dString=null){
//var dString = "2021-04-1 12:00:00";
var d1 = new Date(dString);
var d2 = new Date();
var t2 = d2.getTime();
var t1 = d1.getTime();
var d1Y = d1.getFullYear();
var d2Y = d2.getFullYear();
var d1M = d1.getMonth();
var d2M = d2.getMonth();
var time_obj = {};
time_obj.year = d2.getFullYear()-d1.getFullYear();
time_obj.month = (d2M+12*d2Y)-(d1M+12*d1Y);
time_obj.week = parseInt((t2-t1)/(24*3600*1000*7));
time_obj.day = parseInt((t2-t1)/(24*3600*1000));
time_obj.hour = parseInt((t2-t1)/(3600*1000));
time_obj.minute = parseInt((t2-t1)/(60*1000));
time_obj.second = parseInt((t2-t1)/(1000));
for (const obj_key in time_obj) {
if(time_obj[obj_key] == 0){
delete time_obj[obj_key];
}
}
var ago_text = 'just now';
if(typeof Object.keys(time_obj)[0] != 'undefined'){
var time_key = Object.keys(time_obj)[0];
var time_val = time_obj[Object.keys(time_obj)[0]];
time_key += (time_val > 1) ? 's':'';
ago_text = time_val+' '+time_key+' ago';
}
return ago_text;
}
这是对国际的另一种看法。RelativeTimeFormat
支持过去日期和将来日期 同时接受字符串和日期 易于添加自定义范围(编辑范围) 可以很容易地翻译为Intl.RelativeTimeFormat('ua')
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 }; const secondsElapsed = (date.getTime() - Date.now()) / 1000; for (let key in ranges) { if (ranges[key] < Math.abs(secondsElapsed)) { const delta = secondsElapsed / ranges[key]; return formatter.format(Math.round(delta), key); } } }
https://jsfiddle.net/tv9701uf
我修改了Sky Sanders的版本。Math.floor(…)操作在if块中计算
var timeSince = function(date) {
var seconds = Math.floor((new Date() - date) / 1000);
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
if (seconds < 5){
return "just now";
}else if (seconds < 60){
return seconds + " seconds ago";
}
else if (seconds < 3600) {
minutes = Math.floor(seconds/60)
if(minutes > 1)
return minutes + " minutes ago";
else
return "1 minute ago";
}
else if (seconds < 86400) {
hours = Math.floor(seconds/3600)
if(hours > 1)
return hours + " hours ago";
else
return "1 hour ago";
}
//2 days and no more
else if (seconds < 172800) {
days = Math.floor(seconds/86400)
if(days > 1)
return days + " days ago";
else
return "1 day ago";
}
else{
//return new Date(time).toLocaleDateString();
return date.getDate().toString() + " " + months[date.getMonth()] + ", " + date.getFullYear();
}
}