问题是如何将JavaScript Date格式化为一个字符串,声明时间经过,类似于您在Stack Overflow上看到的时间显示方式。
e.g.
1分钟前 1小时前 1天前 1个月前 一年前
问题是如何将JavaScript Date格式化为一个字符串,声明时间经过,类似于您在Stack Overflow上看到的时间显示方式。
e.g.
1分钟前 1小时前 1天前 1个月前 一年前
当前回答
我修改了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();
}
}
其他回答
我一直在寻找这个问题的答案,并且几乎实现了其中一个解决方案,但一位同事提醒我检查react-intl库,因为我们已经在使用它了。
所以在解决方案中…在使用react-intl库的情况下,它们有一个<FormattedRelative>组件。
https://github.com/yahoo/react-intl/wiki/Components#formattedrelative
function timeSince(date) { var seconds = Math.floor((new Date() - date) / 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"; } var aDay = 24*60*60*1000; console.log(timeSince(new Date(Date.now()-aDay))); console.log(timeSince(new Date(Date.now()-aDay*2)));
我使用这个包:javascript-time-ago
设置TimeAgo 导入TimeAgo 从javascript-time-ago/locale/en.json导入en TimeAgo.addDefaultLocale (en) 写一个函数 // twitter-now是twitter风格。查看文档以获得更多选项 const clockToDateString = (timestamp) => timeAgo。format(new Date(timestamp.toNumber() * 1000), 'twitter-now') 在dom中使用它 < div > {clockToDateString (post.postTime)} < / div >
要使用这个,只需复制所有这些代码,并将其导入到你的组件或任何地方,并将你的ISOstring()日期放在:showTimeAgo("2022-06-20T13:42:29-05:00"),你将获得每个场景的自动时间更新。
旁注:我为这个https://www.npmjs.com/package/showtimeago做了一个npm包
export const showTimeAgo = () => {
const MONTH_NAMES = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
function getOrdinalNum() {
return (
n +
(n > 0
? ['th', 'st', 'nd', 'rd'][
(n > 3 && n < 21) || n % 10 > 3 ? 0 : n % 10
]
: '')
);
}
function getFormattedDate(
date,
preformattedDate = false,
hideYear = false
) {
const day = date.getDate();
const month = MONTH_NAMES[date.getMonth()];
const year = date.getFullYear();
let hours = date.getHours();
let minutes = date.getMinutes();
let ampm = hours >= 12 ? 'pm' : 'am';
switch(true){
case (hours > 12):
hours = hours - 12;
break;
case (hours === 0):
hours = 12;
break;
case(minutes < 10):
minutes = `0${minutes}`;
break;
case(preformattedDate):
// Today at 10:20am
// Yesterday at 10:20am
return `${preformattedDate} at ${hours}:${minutes} ${ampm}`;
case(hideYear):
// January 10th at 10:20pm
return `${month} ${getOrdinalNum(
day
)}, at ${hours}:${minutes} ${ampm}`;
default:
// January 10th 2022 at 10:20pm
return `${month} ${getOrdinalNum(
day
)}, ${year} at ${hours}:${minutes} ${ampm}`;
}
}
// --- Main function
function timeAgo(dateParam) {
if (!dateParam) {
return null;
}
const date =
typeof dateParam === 'object' ? dateParam : new Date(dateParam);
const DAY_IN_MS = 86400000; // 24 * 60 * 60 * 1000
const today = new Date();
const yesterday = new Date(today - DAY_IN_MS);
const seconds = Math.round((today - date) / 1000);
const minutes = Math.round(seconds / 60);
const hour = Math.round(seconds / 3600);
const day = Math.round(seconds / 86400);
const month = Math.round(seconds / 2629800);
const year = Math.floor(seconds / 31536000);
const isToday = today.toDateString() === date.toDateString();
const isYesterday =
yesterday.toDateString() === date.toDateString();
const isThisYear = today.getFullYear() === date.getFullYear();
switch(true){
case (seconds < 5):
return 'now';
case (seconds < 60):
return `${seconds} seconds ago`;
case (seconds < 90):
return 'about a minute ago';
case (minutes < 60):
return `${minutes} minutes ago`;
case (hour === 1 && hour < 2):
return `${hour} hour ago`; // 1 hour ago
case (hour > 1 && hour <= 12):
return `${hour} hours ago`; // 2 hours ago
case (isToday):
return getFormattedDate(date, 'Today'); // Today at 10:20am
case (isYesterday):
return getFormattedDate(date, 'Yesterday'); // Yesterday at 10:20am
case(day > 1 && day <= 30):
return `${day} days ago`; // 2 days ago
case (isThisYear):
return getFormattedDate(date, false, true); // January 10th at 10:20pm
case (day > 30 && month <= 1):
return `${hour} month ago`; // 1 month ago
case (month > 1 && month <= 12):
return `${month} months ago`; // 2 months ago
case (year === 1):
return `${year} year ago`; // 1 year ago
case (year > 1):
return `${year} years ago`; // 2 years ago
default:
return getFormattedDate(date); // January 10th 2022 at 10:20pm
}
}
return timeAgo(date);
};
console.log(showTimeAgo("2022-06-20T13:42:29-05:00"));-05:00"))
这是一个简化版的@sky-sanders的回答。
function timeSince(date) {
var seconds = Math.floor((new Date() - date) / 1000);
var divisors = [31536000, 2592000, 86400, 3600, 60, 1]
var description = ["years", "months", "days", "hours", "minutes", "seconds"]
var result = [];
var interval = seconds;
for (i = 0; i < divisors.length; i++) {
interval = Math.floor(seconds / divisors[i])
if (interval > 1) {
result.push(interval + " " + description[i])
}
seconds -= interval * divisors[i]
}
return result.join(" ")
}