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

e.g.

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


当前回答

我修改了Sky Sanders的版本。Math.floor(…)操作在if块中计算

       var timeSince = function(date) {
            var seconds = Math.floor((new Date() - date) / 1000);
            var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
            if (seconds < 5){
                return "just now";
            }else if (seconds < 60){
                return seconds + " seconds ago";
            }
            else if (seconds < 3600) {
                minutes = Math.floor(seconds/60)
                if(minutes > 1)
                    return minutes + " minutes ago";
                else
                    return "1 minute ago";
            }
            else if (seconds < 86400) {
                hours = Math.floor(seconds/3600)
                if(hours > 1)
                    return hours + " hours ago";
                else
                    return "1 hour ago";
            }
            //2 days and no more
            else if (seconds < 172800) {
                days = Math.floor(seconds/86400)
                if(days > 1)
                    return days + " days ago";
                else
                    return "1 day ago";
            }
            else{

                //return new Date(time).toLocaleDateString();
                return date.getDate().toString() + " " + months[date.getMonth()] + ", " + date.getFullYear();
            }
        }

其他回答

function timeago(date) {
    var seconds = Math.floor((new Date() - date) / 1000);
    if(Math.round(seconds/(60*60*24*365.25)) >= 2) return Math.round(seconds/(60*60*24*365.25)) + " years ago";
    else if(Math.round(seconds/(60*60*24*365.25)) >= 1) return "1 year ago";
    else if(Math.round(seconds/(60*60*24*30.4)) >= 2) return Math.round(seconds/(60*60*24*30.4)) + " months ago";
    else if(Math.round(seconds/(60*60*24*30.4)) >= 1) return "1 month ago";
    else if(Math.round(seconds/(60*60*24*7)) >= 2) return Math.round(seconds/(60*60*24*7)) + " weeks ago";
    else if(Math.round(seconds/(60*60*24*7)) >= 1) return "1 week ago";
    else if(Math.round(seconds/(60*60*24)) >= 2) return Math.round(seconds/(60*60*24)) + " days ago";
    else if(Math.round(seconds/(60*60*24)) >= 1) return "1 day ago";
    else if(Math.round(seconds/(60*60)) >= 2) return Math.round(seconds/(60*60)) + " hours ago";
    else if(Math.round(seconds/(60*60)) >= 1) return "1 hour ago";
    else if(Math.round(seconds/60) >= 2) return Math.round(seconds/60) + " minutes ago";
    else if(Math.round(seconds/60) >= 1) return "1 minute ago";
    else if(seconds >= 2)return seconds + " seconds ago";
    else return seconds + "1 second ago";
}

你可以使用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>

这应该正确地处理任何有效的时间戳,包括Date.now()、单数单位和未来日期。我漏掉了月份,但是这些月份应该很容易加进去。我尽量保持它的可读性。

function getTimeInterval(date) { let seconds = Math.floor((Date.now() - date) / 1000); let unit = "second"; let direction = "ago"; if (seconds < 0) { seconds = -seconds; direction = "from now"; } let value = seconds; if (seconds >= 31536000) { value = Math.floor(seconds / 31536000); unit = "year"; } else if (seconds >= 86400) { value = Math.floor(seconds / 86400); unit = "day"; } else if (seconds >= 3600) { value = Math.floor(seconds / 3600); unit = "hour"; } else if (seconds >= 60) { value = Math.floor(seconds / 60); unit = "minute"; } if (value != 1) unit = unit + "s"; return value + " " + unit + " " + direction; } console.log(getTimeInterval(Date.now())); // 0 seconds ago console.log(getTimeInterval(Date.now() + 1000)); // 1 second from now console.log(getTimeInterval(Date.now() - 1000)); // 1 second ago console.log(getTimeInterval(Date.now() + 60000)); // 1 minute from now console.log(getTimeInterval(Date.now() - 120000)); // 2 minutes ago console.log(getTimeInterval(Date.now() + 120000)); // 2 minutes from now console.log(getTimeInterval(Date.now() + 3600000)); // 1 hour from now console.log(getTimeInterval(Date.now() + 360000000000)); // 11 years from now console.log(getTimeInterval(0)); // 49 years ago

我使用这个包:javascript-time-ago

设置TimeAgo 导入TimeAgo 从javascript-time-ago/locale/en.json导入en TimeAgo.addDefaultLocale (en) 写一个函数 // twitter-now是twitter风格。查看文档以获得更多选项 const clockToDateString = (timestamp) => timeAgo。format(new Date(timestamp.toNumber() * 1000), 'twitter-now') 在dom中使用它 < div > {clockToDateString (post.postTime)} < / div >

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