问题是如何将JavaScript Date格式化为一个字符串,声明时间经过,类似于您在Stack Overflow上看到的时间显示方式。
e.g.
1分钟前 1小时前 1天前 1个月前 一年前
问题是如何将JavaScript Date格式化为一个字符串,声明时间经过,类似于您在Stack Overflow上看到的时间显示方式。
e.g.
1分钟前 1小时前 1天前 1个月前 一年前
当前回答
您可能需要查看humanized_time_span: https://github.com/layam/js_humanized_time_span
它与框架无关,并且完全可定制。
只需下载/包含脚本,然后你可以这样做:
humanized_time_span("2011-05-11 12:00:00")
=> '3 hours ago'
humanized_time_span("2011-05-11 12:00:00", "2011-05-11 16:00:00)
=> '4 hours ago'
甚至是这样:
var custom_date_formats = {
past: [
{ ceiling: 60, text: "less than a minute ago" },
{ ceiling: 86400, text: "$hours hours, $minutes minutes and $seconds seconds ago" },
{ ceiling: null, text: "$years years ago" }
],
future: [
{ ceiling: 60, text: "in less than a minute" },
{ ceiling: 86400, text: "in $hours hours, $minutes minutes and $seconds seconds time" },
{ ceiling: null, text: "in $years years" }
]
}
humanized_time_span("2010/09/10 10:00:00", "2010/09/10 10:00:05", custom_date_formats)
=> "less than a minute ago"
更多信息请阅读文档。
其他回答
将上面的函数更改为
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时间戳。
回复@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++]); } } }
可读性强且跨浏览器兼容的代码:
@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'));
我还没有检查(虽然这并不难),但我认为Stack Exchange站点使用jquery。Timeago插件来创建这些时间字符串。
这个插件使用起来很简单,而且很干净,还能自动更新。
下面是一个简单的例子(来自插件的主页):
First, load jQuery and the plugin: <script src="jquery.min.js" type="text/javascript"></script> <script src="jquery.timeago.js" type="text/javascript"></script> Now, let's attach it to your timestamps on DOM ready: jQuery(document).ready(function() { jQuery("abbr.timeago").timeago(); }); This will turn all abbr elements with a class of timeago and an ISO 8601 timestamp in the title: <abbr class="timeago" title="2008-07-17T09:24:17Z">July 17, 2008</abbr> into something like this: <abbr class="timeago" title="July 17, 2008">about a year ago</abbr> which yields: about a year ago. As time passes, the timestamps will automatically update.
在这种情况下可能有点过头了,但如果有机会,moment.js真的很棒!
js是一个javascript datetime库,在这种情况下使用它,你需要做:
moment(yourdate).fromNow()
http://momentjs.com/docs/#/displaying/fromnow/
2018附录:Luxon是一个新的现代图书馆,可能值得一看!
2022年附录:Day.js是一个较新的库,比Luxon轻80%左右,具有类似的功能。