问题是如何将JavaScript Date格式化为一个字符串,声明时间经过,类似于您在Stack Overflow上看到的时间显示方式。

e.g.

1分钟前 1小时前 1天前 1个月前 一年前


当前回答

我使用了可能11的旧答案,并添加了Intl。用于翻译的RelativeTimeFormat。

https://stackoverflow.com/a/73331658/673809

function timeAgo (value) { const seconds = Math.floor((new Date().getTime() - new Date(value).getTime()) / 1000) let interval = seconds / 31536000 const rtf = new Intl.RelativeTimeFormat("en", { numeric: 'auto' }) if (interval > 1) { return rtf.format(-Math.floor(interval), 'year') } interval = seconds / 2592000 if (interval > 1) { return rtf.format(-Math.floor(interval), 'month') } interval = seconds / 86400 if (interval > 1) { return rtf.format(-Math.floor(interval), 'day') } interval = seconds / 3600 if (interval > 1) { return rtf.format(-Math.floor(interval), 'hour') } interval = seconds / 60 if (interval > 1) { return rtf.format(-Math.floor(interval), 'minute') } return rtf.format(-Math.floor(interval), 'second') } console.log(timeAgo('2022-08-12 20:50:20'))

其他回答

下面是我所做的(对象返回时间单位及其值):

function timeSince(post_date, reference) { var reference = reference ? new Date(reference) : new Date(), diff = reference - new Date(post_date + ' GMT-0000'), date = new Date(diff), object = { unit: null, value: null }; if (diff < 86400000) { var secs = date.getSeconds(), mins = date.getMinutes(), hours = date.getHours(), array = [ ['second', secs], ['minute', mins], ['hour', hours] ]; } else { var days = date.getDate(), weeks = Math.floor(days / 7), months = date.getMonth(), years = date.getFullYear() - 1970, array = [ ['day', days], ['week', weeks], ['month', months], ['year', years] ]; } for (var i = 0; i < array.length; i++) { array[i][0] += array[i][1] != 1 ? 's' : ''; object.unit = array[i][1] >= 1 ? array[i][0] : object.unit; object.value = array[i][1] >= 1 ? array[i][1] : object.value; } return object; }

我还没有检查(虽然这并不难),但我认为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.

你可以使用Luxon:

DateTime.toRelative()

https://moment.github.io/luxon/api-docs/index.html#datetimetorelative

这里还有一些例子:

const DateTime = luxon.DateTime; // toRelative console.log(DateTime.now().minus({ seconds: 1 }).toRelative()) // 1 second ago console.log(DateTime.now().minus({ seconds: 10 }).toRelative()) // 10 seconds ago console.log(DateTime.now().minus({ days: 2 }).toRelative()) console.log(DateTime.now().minus({ years: 3 }).toRelative()) console.log(DateTime.now().plus({ years: 3 }).toRelative()) console.log(DateTime.now().plus({ days: 2 }).toRelative()) console.log(DateTime.now().plus({ seconds: 1 }).toRelative()) console.log(DateTime.now().plus({ seconds: 10 }).toRelative()) // toRelativeCalendar console.log(DateTime.now().minus({ seconds: 1 }).toRelativeCalendar()) // today console.log(DateTime.now().minus({ seconds: 10 }).toRelativeCalendar()) // today console.log(DateTime.now().minus({ days: 2 }).toRelativeCalendar()) console.log(DateTime.now().minus({ years: 3 }).toRelativeCalendar()) console.log(DateTime.now().plus({ years: 3 }).toRelativeCalendar()) console.log(DateTime.now().plus({ days: 2 }).toRelativeCalendar()) console.log(DateTime.now().plus({ seconds: 1 }).toRelativeCalendar()) console.log(DateTime.now().plus({ seconds: 10 }).toRelativeCalendar()) <script src="https://moment.github.io/luxon/global/luxon.min.js"></script>

要使用这个,只需复制所有这些代码,并将其导入到你的组件或任何地方,并将你的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"))

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