問題描述
我想以人性化的格式顯示一些相對于當前日期的日期.
I'd like to display some dates as relative to the current date in a human-friendly format.
人類友好的相對日期示例:
Examples of human-friendly relative dates:
- 10 秒前
- 20 分鐘后
- 1 天前
- 5 周前
- 2 個月前
基本上忠實地保留最高數量級(并且優先考慮,僅在超過其中 2 個單位時上調單位 - 5 周而不是 1 個月).
Basically faithfully preserving the highest order of magnitude (and by preference, only shifting up units when passing 2 of those units - 5 weeks instead of 1 month).
雖然我可以接受一個控制較少且日期更友好的圖書館,例如:
Though I could live with a library that had less control and even more friendly dates like:
- 昨天
- 明天
- 上周
- 幾分鐘前
- 幾個小時后
有任何流行的圖書館嗎?
Any popular libraries for this?
推薦答案
自從我寫了這個答案,一個眾所周知的可用庫是 moment.js.
Since I wrote this answer, a well known library available is moment.js.
有可用的庫,但自己實現它很簡單.只需使用少數幾個條件.
There are libraries available, but it is trivial to implement it yourself. Just use a handful of conditions.
假設 date
是一個實例化的 Date
對象,用于您要與之進行比較的時間.
Assume date
is an instantiated Date
object for the time you want to make a comparison against.
// Make a fuzzy time
var delta = Math.round((+new Date - date) / 1000);
var minute = 60,
hour = minute * 60,
day = hour * 24,
week = day * 7;
var fuzzy;
if (delta < 30) {
fuzzy = 'just then.';
} else if (delta < minute) {
fuzzy = delta + ' seconds ago.';
} else if (delta < 2 * minute) {
fuzzy = 'a minute ago.'
} else if (delta < hour) {
fuzzy = Math.floor(delta / minute) + ' minutes ago.';
} else if (Math.floor(delta / hour) == 1) {
fuzzy = '1 hour ago.'
} else if (delta < day) {
fuzzy = Math.floor(delta / hour) + ' hours ago.';
} else if (delta < day * 2) {
fuzzy = 'yesterday';
}
您需要調整它以處理未來的日期.
You would need to adapt this to handle future dates.
這篇關于用于人類友好的相對日期格式的 Javascript 庫的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!