DIV CSS 佈局教程網

實作「幾分鐘前」這類人性化時間差顯示
編輯:JavaScript綜合知識     

新浪微博之類的網站不會直接顯示「2011-05-12 14:30」,而是「發表於 5 分鐘前」。這種換算比絕對時間更直觀,用 JavaScript 就能做到。

做法一:換算成單位的 JavaScript 函數

var minute = 1000 * 60;
var hour = minute * 60;
var day = hour * 24;
var halfamonth = day * 15;
var month = day * 30;

function getDateDiff(dateTimeStamp){
 var now = new Date().getTime();
 var diffValue = now - dateTimeStamp;
 if(diffValue < 0){ /* 結束日期不能小於開始日期 */ }

 var monthC = diffValue / month;
 var weekC = diffValue / (7 * day);
 var dayC = diffValue / day;
 var hourC = diffValue / hour;
 var minC = diffValue / minute;

 if(monthC >= 1){ result = "發表於" + parseInt(monthC) + "個月前"; }
 else if(weekC >= 1){ result = "發表於" + parseInt(weekC) + "周前"; }
 else if(dayC >= 1){ result = "發表於" + parseInt(dayC) + "天前"; }
 else if(hourC >= 1){ result = "發表於" + parseInt(hourC) + "個小時前"; }
 else if(minC >= 1){ result = "發表於" + parseInt(minC) + "分鐘前"; }
 else result = "剛剛發表";
 return result;
}

若拿到的不是時間戳,可以先用這個函數把字串轉掉,功能等同 JS 版的 strtotime:

function getDateTimeStamp(dateStr){
 return Date.parse(dateStr.replace(/-/gi, "/"));
}

做法二:只顯示天、小時、分鐘

function jsDateDiff(publishTime){
 var d_minutes, d_hours, d_days;
 var timeNow = parseInt(new Date().getTime() / 1000);
 var d = timeNow - publishTime;
 d_days = parseInt(d / 86400);
 d_hours = parseInt(d / 3600);
 d_minutes = parseInt(d / 60);

 if(d_days > 0 && d_days < 4){
 return d_days + "天前";
 } else if(d_days <= 0 && d_hours > 0){
 return d_hours + "小時前";
 } else if(d_hours <= 0 && d_minutes > 0){
 return d_minutes + "分鐘前";
 } else {
 var s = new Date(publishTime * 1000);
 return (s.getMonth() + 1) + "月" + s.getDate() + "日";
 }
}

注意這裡的 publishTime 是秒而非毫秒,所以要乘 1000。

做法三:用 timeago 外掛

HTML 寫法,把時間放在 title 或 datetime 屬性:

<span class="time timeago" title="2014-10-17 09:30:00"></span>

呼叫:

jQuery("span.timeago").timeago();

外掛核心的換算邏輯是這樣的(節錄):

$.timeago = function(timestamp) {
 if (timestamp instanceof Date) {
 return inWords(timestamp);
 } else if (typeof timestamp === "string") {
 return inWords($.timeago.parse(timestamp));
 } else if (typeof timestamp === "number") {
 return inWords(new Date(timestamp));
 } else {
 return inWords($.timeago.datetime(timestamp));
 }
};

$.extend($.timeago, {
 settings: {
 refreshMillis: 60000,
 allowFuture: false,
 cutoff: 0,
 strings: {
 prefixAgo: null,
 prefixFromNow: null,
 suffixAgo: "前",
 suffixFromNow: "from now",
 seconds: "1分鐘",
 minute: "1分鐘",
 minutes: "%d分鐘",
 hour: "1小時",
 hours: "%d小時",
 day: "1天",
 days: "%d天",
 month: "1月",
 months: "%d月",
 year: "1年",
 years: "%d年",
 wordSeparator: "",
 numbers: []
 }
});

// inWords 的核心比較
var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
 seconds < 90 && substitute($l.minute, 1) ||
 minutes < 45 && substitute($l.minutes, Math.round(minutes)) ||
 minutes < 90 && substitute($l.hour, 1) ||
 hours < 24 && substitute($l.hours, Math.round(hours)) ||
 hours < 42 && substitute($l.day, 1) ||
 days < 30 && substitute($l.days, Math.round(days)) ||
 days < 45 && substitute($l.month, 1) ||
 days < 365 && substitute($l.months, Math.round(days / 30)) ||
 years < 1.5 && substitute($l.year, 1) ||
 substitute($l.years, Math.round(years));

parse 方法負責把 ISO8601 字串正規化:

parse: function(iso8601) {
 var s = $.trim(iso8601);
 s = s.replace(/\.\d+/,""); // 移除毫秒
 s = s.replace(/-/,"/").replace(/-/,"/");
 s = s.replace(/T/," ").replace(/Z/," UTC");
 s = s.replace(/([+-]\d\d):?(\d\d)/," $1$2"); // -04:00 → -0400
 return new Date(s);
}

外掛還提供了 update 與 updateFromDOM 兩個方法,可以在不重新初始化的情況下更新時間,並以 refreshMillis 設定自動刷新間隔(預設 60 秒)。

三種做法各有取捨:自己寫最精簡、可控性最高;用外掛則省去多語言與邊界條件(45 秒、90 分鐘)的處理細節。但要留意,這種相對時間是靜態計算的結果,頁面開著不動就不會更新,需要時記得設reste 定 timer 重新渲染。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved