头图
Recently, there is a need to convert the publication time of an article or comment into, just, 10 minutes ago.... This representation is as follows:

IICOOM格式化过去时间

JavaScript formatting time

 /**
 * 格式化 已经过去的时间
 * @param {*} value 时间戳(ms) 或时间对象
 * @returns 
 */
function elapsed(value) {

    const time = Date.now() - new Date(value)

    const times = [31536000000, 2592000000, 86400000, 3600000, 60000, 1000] 
    const units = ['年前', '月前', '天前', '小时前', '分钟前', '秒前']

    let index = times.findIndex(t => t < time)

    return Math.round(time/times[index]) + units[index]
}

console.log(elapsed(1649743490030))
// 14秒前

Through the above method, the initial realization. However, it still feels that the processing of units is too rigid, and we need to refer to other websites for optimization in the future.

Improve

For the units above, we can actually change 'seconds ago' to 'just now', that is, less than 1 minute is represented as just now, and the direct display date greater than one day:

 /**
 * 格式化 已经过去的时间
 * @param {*} value 时间戳(ms) 或时间对象
 * @returns 
 */
function elapsed(value) {
    const time = Date.now() - new Date(value)
    const times = [3600000, 60000, 1000]
    const units = [' 小时前', ' 分钟前', ' 刚刚']
    if (time > 86400000) {
      return globalFunction.format(value, 'YYYY-MM-DD HH:mm')
    } else {
      let index = times.findIndex(t => t < time)
      return [-1,2].includes(index)?units[2]:Math.round(time/times[index]) + units[index]
    }
}

/**
 * 13位时间戳
 * @param {*} value 
 * @returns 
 */
function format(value, format) {
    let date = new Date(value);
    let year = date.getFullYear();
    let month = ("0" + (date.getMonth() + 1)).slice(-2);
    let day = ("0" + date.getDate()).slice(-2);
    let hour = ("0" + date.getHours()).slice(-2);
    let minute = ("0" + date.getMinutes()).slice(-2);
    let second = ("0" + date.getSeconds()).slice(-2);
    // 拼接
    if (!format) {
      return year + "-"+ month +"-"+ day +" "+ hour +":"+ minute+":"+second;
    }
    if (format === 'YYYY-MM-DD HH:mm') {
      return year + "-"+ month +"-"+ day +" "+ hour +":"+ minute;
    }
}

In this way, it seems a lot more reasonable.


来了老弟
508 声望31 粉丝

纸上得来终觉浅,绝知此事要躬行