【JavaScript】处理时间,当前时间加减法

先封装个方法:

/**
 * @description: 获取当前时间和进行推算后的时间(stime, etime)
 * @param {number} period - 向前推算的时间(s)
 * @return {*}
 */
handleTimeString(period) {
    let etime, stime, timeString, newStime
    // 当前时间:格式YYYY-MM-DD HH:MM:SS
    etime = new Date().toLocaleDateString().replace(/\//g, "-") + " " + new Date().toTimeString().split(" ")[0]
    // 将当前时间包装成标准时间
    timeString = new Date(etime)
    // 将以秒(s)为单位进行演算后的时间包装成标准时间
    stime = new Date(timeString.setTime(timeString.getTime() - period))
    // 演算后的时间:格式YYYY-MM-DD HH:MM:SS
    newStime = stime.toLocaleDateString().replace(/\//g, "-") + " " + stime.toTimeString().split(" ")[0]
    // 以对象的形式返回
    return {
        stime: newStime,
        etime: etime,
    }
},

实操:

切换时间:全部转换成秒

switch (timeLimit) {
    let timeObj = {}
    case "10min":
       timeObj = this.handleTimeString(10 * 60 * 1000)
       break
    case "30min":
       timeObj = this.handleTimeString(30 * 60 * 1000)
       break
    case "1h":
       timeObj = this.handleTimeString(60 * 60 * 1000)
       break
    case "12h":
       timeObj = this.handleTimeString(12 * 60 * 60 * 1000)
       break
    case "1d":
       timeObj = this.handleTimeString(24 * 60 * 60 * 1000)
       break
    case "3d":
       timeObj = this.handleTimeString(3 * 24 * 60 * 60 * 1000)
       break
}

效果:

image


Keep foolish, keep hungry.

你可能感兴趣的:(javascript前端)