DIV CSS 佈局教程網

把時間顯示成「幾分鐘前、幾小時前、幾天前」的多種做法
編輯:關於JavaScript     

社群網站的動態時報、論壇的最後回覆時間,通常不會直接顯示 2024-05-01 14:32,而是「3 分鐘前」。這種「相對時間」實作起來有幾種層次不同的方案。

方案一:前端用 jQuery 外掛

後端只存時間戳,前端交給 smart-time-ago 這類外掛轉換。好處是語系與更新頻率都由外掛處理。

方案二:在模板層計算(FreeMarker 範例)

若使用 FreeMarker,可以直接寫成巨集,把 datetime 傳進去即可:

<#macro timeline_dt datetime=.now>
<#assign ct = (.now?long - datetime?long) / 1000>
<#if ct gte 31104000><#--n 年前-->${(ct/31104000)?int}年前<#t>
<#elseif ct gte 2592000><#--n 月前-->${(ct/2592000)?int}個月前<#t>
<#elseif ct gte 86400*2><#--n 天前-->${(ct/86400)?int}天前<#t>
<#elseif ct gte 86400><#--1 天前-->昨天<#t>
<#elseif ct gte 3600><#--n 小時前-->${(ct/3600)?int}小時前<#t>
<#elseif ct gte 60><#--n 分鐘前-->${(ct/60)?int}分鐘前<#t>
<#elseif ct gt 0><#--n 秒前-->${ct?int}秒前<#t>
<#else>剛剛
</#if>
</#macro>

方案三:Java 端用 PrettyTime

public static void main(String[] args) {
    PrettyTime p = new PrettyTime();
    System.out.println(p.format(DateUtils.addDays(new Date(), 2)));
}

方案四:自寫 Java 工具方法

private final static long minute = 60 * 1000;         // 1 分鐘
private final static long hour   = 60 * minute;       // 1 小時
private final static long day    = 24 * hour;         // 1 天
private final static long month  = 31 * day;          // 月
private final static long year   = 12 * month;        // 年

/**
 * 回傳文字描述的日期
 * @param date 目標時間
 * @return 例如「3天前」
 */
public static String getTimeFormatText(Date date) {
    if (date == null) {
        return null;
    }
    long diff = new Date().getTime() - date.getTime();
    long r = 0;

    if (diff > year)  { r = (diff / year);  return r + "年前"; }
    if (diff > month) { r = (diff / month); return r + "個月前"; }
    if (diff > day)   { r = (diff / day);   return r + "天前"; }
    if (diff > hour)  { r = (diff / hour);  return r + "個小時前"; }
    if (diff > minute){ r = (diff / minute);return r + "分鐘前"; }
    return "剛剛";
}

方案五:純 JavaScript 外掛 timeago.js

原版 Smart Time Ago 會依時間遠近自動調整刷新頻率(每分鐘、每 22 分鐘、每 30 分鐘、每 12 小時),避免不必要的定時器:

// Smart Time Ago v0.1.0
// Copyright 2012, Terry Tai, Pragmatic.ly
// https://pragmatic.ly/
// Licensed under the MIT license.
(function () {
    var TimeAgo;
    TimeAgo = (function () {
        function TimeAgo(element, options) {
            this.startInterval = 60000;
            this.init(element, options);
        }
        TimeAgo.prototype.init = function (element, options) {
            this.$element = $(element);
            this.options = $.extend({}, $.fn.timeago.defaults, options);
            this.updateTime();
            return this.startTimer();
        };
        TimeAgo.prototype.startTimer = function () {
            var self = this;
            return this.interval = setInterval((function () {
                return self.refresh();
            }), this.startInterval);
        };
        TimeAgo.prototype.stopTimer = function () {
            return clearInterval(this.interval);
        };
        TimeAgo.prototype.restartTimer = function () {
            this.stopTimer();
            return this.startTimer();
        };
        TimeAgo.prototype.refresh = function () {
            this.updateTime();
            return this.updateInterval();
        };
        TimeAgo.prototype.updateTime = function () {
            var self = this;
            return this.$element.findAndSelf(this.options.selector).each(function () {
                var timeAgoInWords;
                timeAgoInWords = self.timeAgoInWords($(this).attr(self.options.attr));
                return $(this).html(timeAgoInWords);
            });
        };
        TimeAgo.prototype.updateInterval = function () {
            var filter, newestTime, newestTimeInMinutes, newestTimeSrc;
            if (this.$element.findAndSelf(this.options.selector).length > 0) {
                if (this.options.dir === "up") {
                    filter = ":first";
                } else if (this.options.dir === "down") {
                    filter = ":last";
                }
                newestTimeSrc = this.$element.findAndSelf(this.options.selector).filter(filter).attr(this.options.attr);
                newestTime = this.parse(newestTimeSrc);
                newestTimeInMinutes = this.getTimeDistanceInMinutes(newestTime);

                if (newestTimeInMinutes >= 0 && newestTimeInMinutes <= 44
                    && this.startInterval !== 60000) {
                    this.startInterval = 60000;
                    return this.restartTimer();
                } else if (newestTimeInMinutes >= 45 && newestTimeInMinutes <= 89
                    && this.startInterval !== 60000 * 22) {
                    this.startInterval = 60000 * 22;
                    return this.restartTimer();
                } else if (newestTimeInMinutes >= 90 && newestTimeInMinutes <= 2519
                    && this.startInterval !== 60000 * 30) {
                    this.startInterval = 60000 * 30;
                    return this.restartTimer();
                } else if (newestTimeInMinutes >= 2520
                    && this.startInterval !== 60000 * 60 * 12) {
                    this.startInterval = 60000 * 60 * 12;
                    return this.restartTimer();
                }
            }
        };
        TimeAgo.prototype.timeAgoInWords = function (timeString) {
            var absolutTime;
            absolutTime = this.parse(timeString);
            return this.distanceOfTimeInWords(absolutTime) + (this.options.lang.suffix);
        };
        TimeAgo.prototype.parse = function (iso8601) {
            var timeStr;
            timeStr = $.trim(iso8601);
            timeStr = timeStr.replace(/\.\d\d\d+/, "");
            timeStr = timeStr.replace(/-/, "/").replace(/-/, "/");
            timeStr = timeStr.replace(/T/, " ").replace(/Z/, " UTC");
            timeStr = timeStr.replace(/([\+\-]\d\d)\:?(\d\d)/, " $1$2");
            return new Date(timeStr);
        };
        TimeAgo.prototype.getTimeDistanceInMinutes = function (absolutTime) {
            var timeDistance;
            timeDistance = new Date().getTime() - absolutTime.getTime();
            return Math.round((Math.abs(timeDistance) / 1000) / 60);
        };
        TimeAgo.prototype.distanceOfTimeInWords = function (absolutTime) {
            var dim;
            dim = this.getTimeDistanceInMinutes(absolutTime);
            if (dim === 0) {
                return "" + this.options.lang.prefixes.lt + " " + this.options.lang.units.minute;
            } else if (dim === 1) {
                return "1 " + this.options.lang.units.minute;
            } else if (dim >= 2 && dim <= 44) {
                return "" + dim + " " + this.options.lang.units.minutes;
            } else if (dim >= 45 && dim <= 89) {
                return "" + this.options.lang.prefixes.about + " 1 " + this.options.lang.units.hour;
            } else if (dim >= 90 && dim <= 1439) {
                return "" + this.options.lang.prefixes.about + " " + (Math.round(dim / 60)) + " " + this.options.lang.units.hours;
            } else if (dim >= 1440 && dim <= 2519) {
                return "1 " + this.options.lang.units.day;
            } else if (dim >= 2520 && dim <= 43199) {
                return "" + (Math.round(dim / 1440)) + " " + this.options.lang.units.days;
            } else if (dim >= 43200 && dim <= 86399) {
                return "" + this.options.lang.prefixes.about + " 1 " + this.options.lang.units.month;
            } else if (dim >= 86400 && dim <= 525599) {
                return "" + (Math.round(dim / 43200)) + " " + this.options.lang.units.months;
            } else if (dim >= 525600 && dim <= 655199) {
                return "" + this.options.lang.prefixes.about + " 1 " + this.options.lang.units.year;
            } else if (dim >= 655200 && dim <= 914399) {
                return "" + this.options.lang.prefixes.over + " 1 " + this.options.lang.units.year;
            } else if (dim >= 914400 && dim <= 1051199) {
                return "" + this.options.lang.prefixes.almost + " 2 " + this.options.lang.units.years;
            } else {
                return "" + this.options.lang.prefixes.about + " " + (Math.round(dim / 525600)) + " " + this.options.lang.units.years;
            }
        };
        return TimeAgo;
    })();

    $.fn.timeago = function (options) {
        if (options == null) options = {};
        return this.each(function () {
            var $this, data;
            $this = $(this);
            data = $this.data("timeago");
            if (!data) $this.data("timeago", new TimeAgo(this, options));
            if (typeof options === 'string') return data[options]();
        });
    };
    $.fn.findAndSelf = function (selector) {
        return this.find(selector).add(this.filter(selector));
    };
    $.fn.timeago.Constructor = TimeAgo;
    $.fn.timeago.defaults = {
        selector: 'time.timeago',
        attr: 'datetime',
        dir: 'up',
        lang: {
            units: {
                second: "second", seconds: "seconds",
                minute: "minute", minutes: "minutes",
                hour: "hour", hours: "hours",
                day: "day", days: "days",
                month: "month", months: "months",
                year: "year", years: "years"
            },
            prefixes: { lt: "less than a", about: "about", over: "over", almost: "almost" },
            suffix: ' ago'
        }
    };
}).call(this);

中文版(簡化+中文化)的 timeago.js:

(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD,註冊為匿名模組
        define(['jquery'], factory);
    } else {
        // 瀏覽器全域
        factory(jQuery);
    }
}(function ($) {
    $.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));
        }
    };
    var $t = $.timeago;

    $.extend($.timeago, {
        settings: {
            refreshMillis: 60000,
            allowFuture: false,
            localeTitle: 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: function (distanceMillis) {
            var $l = this.settings.strings;
            var prefix = $l.prefixAgo;
            var suffix = $l.suffixAgo;

            if (this.settings.allowFuture) {
                if (distanceMillis < 0) {
                    prefix = $l.prefixFromNow;
                    suffix = $l.suffixFromNow;
                }
            }

            var seconds = Math.abs(distanceMillis) / 1000;
            var minutes = seconds / 60;
            var hours   = minutes / 60;
            var days    = hours / 24;
            var years   = days / 365;

            function substitute(stringOrFunction, number) {
                var string = $.isFunction(stringOrFunction)
                    ? stringOrFunction(number, distanceMillis)
                    : stringOrFunction;
                var value = ($l.numbers && $l.numbers[number]) || number;
                return string.replace(/%d/i, value);
            }

            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));

            var separator = $l.wordSeparator || "";
            if ($l.wordSeparator === undefined) {
                separator = " ";
            }
            return $.trim([prefix, words, suffix].join(separator));
        },

        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);
        },

        datetime: function (elem) {
            var iso8601 = $t.isTime(elem) ? $(elem).attr("datetime") : $(elem).attr("title");
            return $t.parse(iso8601);
        },

        isTime: function (elem) {
            // jQuery 的 is() 在舊 IE 下對 HTML5 元素支援不佳
            return $(elem).get(0).tagName.toLowerCase() === "time";
        }
    });

    // 可透過 $(el).timeago('action') 呼叫的函式
    var functions = {
        init: function () {
            var refresh_el = $.proxy(refresh, this);
            refresh_el();
            var $s = $t.settings;
            if ($s.refreshMillis > 0) {
                setInterval(refresh_el, $s.refreshMillis);
            }
        },
        update: function (time) {
            $(this).data('timeago', { datetime: $t.parse(time) });
            refresh.apply(this);
        },
        updateFromDOM: function () {
            $(this).data('timeago', {
                datetime: $t.parse($t.isTime(this) ? $(this).attr("datetime") : $(this).attr("title"))
            });
            refresh.apply(this);
        }
    };

    $.fn.timeago = function (action, options) {
        var fn = action ? functions[action] : functions.init;
        if (!fn) {
            throw new Error("Unknown function name '" + action + "' for timeago");
        }
        this.each(function () {
            fn.call(this, options);
        });
        return this;
    };

    function refresh() {
        var data = prepareData(this);
        var $s = $t.settings;
        if (!isNaN(data.datetime)) {
            if ($s.cutoff == 0 || distance(data.datetime) < $s.cutoff) {
                $(this).text(inWords(data.datetime));
            }
        }
        return this;
    }

    function prepareData(element) {
        element = $(element);
        if (!element.data("timeago")) {
            element.data("timeago", { datetime: $t.datetime(element) });
            var text = $.trim(element.text());
            if ($t.settings.localeTitle) {
                element.attr("title", element.data('timeago').datetime.toLocaleString());
            } else if (text.length > 0 && !($t.isTime(element) && element.attr("title"))) {
                element.attr("title", text);
            }
        }
        return element.data("timeago");
    }

    function inWords(date) {
        return $t.inWords(distance(date));
    }

    function distance(date) {
        return (new Date().getTime() - date.getTime());
    }

    // 修正 IE6 無法建立未知元素
    document.createElement("abbr");
    document.createElement("time");
}));

建議:自己寫一個 20 行的版本

如果不想引入外掛,純 JavaScript 的核心邏輯其實很短:

function timeAgo(date) {
    var seconds = Math.floor((Date.now() - new Date(date).getTime()) / 1000);

    var units = [
        [31536000, '年'],
        [2592000,  '個月'],
        [86400,    '天'],
        [3600,     '小時'],
        [60,       '分鐘'],
        [1,        '秒']
    ];

    if (seconds < 5) return '剛剛';

    for (var i = 0; i < units.length; i++) {
        var size = units[i][0], label = units[i][1];
        if (seconds >= size) {
            var n = Math.floor(seconds / size);
            return n + ' ' + label + '前';
        }
    }
    return '剛剛';
}

console.log(timeAgo(Date.now() - 90 * 1000));   // 1 分鐘前

兩個容易忽略的細節

  • 絕對時間不要丟掉:建議在元素上保留 datetime 屬性與 title 供滑過時查看精確時間,也利於 SEO 與無障礙閱讀。
  • 未來時間要處理:伺服器與用戶端時鐘不盡一致,算出負數時應顯示「剛剛」或改用絕對時間,避免出現「-3 分鐘前」。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved