How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

后端 未结 25 1902
遥遥无期
遥遥无期 2020-11-22 12:57

The question is how to format a JavaScript Date as a string stating the time elapsed similar to the way you see times displayed on Stack Overflow.

e.g.<

25条回答
  •  自闭症患者
    2020-11-22 13:12

    An ES6 version of the code provided by @user1012181

    // Epochs
    const epochs = [
        ['year', 31536000],
        ['month', 2592000],
        ['day', 86400],
        ['hour', 3600],
        ['minute', 60],
        ['second', 1]
    ];
    
    
    // Get duration
    const getDuration = (timeAgoInSeconds) => {
        for (let [name, seconds] of epochs) {
            const interval = Math.floor(timeAgoInSeconds / seconds);
    
            if (interval >= 1) {
                return {
                    interval: interval,
                    epoch: name
                };
            }
        }
    };
    
    
    // Calculate
    const timeAgo = (date) => {
        const timeAgoInSeconds = Math.floor((new Date() - new Date(date)) / 1000);
        const {interval, epoch} = getDuration(timeAgoInSeconds);
        const suffix = interval === 1 ? '' : 's';
    
        return `${interval} ${epoch}${suffix} ago`;
    };
    

    Edited with @ibe-vanmeenen suggestions. (Thanks !)

提交回复
热议问题