使用JS将 时间戳 和 Date对象 相互转换

时间戳 和 Date对象 相互转换

将Date对象转换成时间戳

  • 使用Number()
    let newDate = new Date()
    // 返回当前时间的时间戳
    Number(newDate)
  • 使用Date.parse()
    let newDate = new Date()
    // 返回当前时间戳
    Date.parse(newDate)
  • 利用转义符进行转义
    // 使用“+”对时间对象进行转义
    let newDate = +new Date()

将时间戳转换为Date对象

  • 实例化一个Date对象,并将13位的时间戳传入
    let newDate = new Date(时间戳)
  • 使用Date.setTime(),设置Date对象的时间为时间戳的时间
    // 时间戳
    let timestamp = 1538148600000
    // 实例一个时间戳对象
    let newDate = new Date()
    // 设置Date对象的时间为时间戳的时间
    newDate.setTime(tiemstamp)

实例1:格式化时间戳

将时间戳转换为日期,时间格式为:'yyyy-MM-dd hh:mm:ss'
欲了解RegExp.$n的相关知识可以访问链接:$1...$9 属性 (RegExp) (JavaScript)

/*
* value为时间戳,fmt为时间格式('yyyy-MM-dd hh:mm:ss')
* @param { Number | Date } value
* @param { String } fmt
* 格式化完成的时间
* @return { String } fmt 
*/
const dateFmt = (value, fmt) => {
    if(typeof value !== undefined) {
        value = new Date(value)
        const fmtObj = {
            'M+': value.getMonth() + 1, // 月份
            'd+': value.getDate(), // 日期
            'h+': value.getHours(), // 小时
            'm+': value.getMinutes(), // 分钟
            's+': value.getSeconds(), // 秒
            'q+': Math.floor((value.getMonth() + 3) / 3), //季度
            'S': value.getMilliseconds() // 毫秒
        }
        if (/(y+)/.test(fmt)) {
            // fmt = fmt.replace(Reg.Exp.$1,(value.getFullYear() + '').substr(4 - RegExp.$1.length));
            fmt = fmt.replace(/(y+)/, (value.getFullYear() + '').substr(4 - RegExp.$1.length))
        }
        for (let key in fmtObj) {
            let regExp = new RegExp('(' + key + ')')
            if (regExp.test(fmt)) {
               //fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (fmtObj[key]) : (('00' + fmtObj[key]).substr(('' + fmtObj[key]).length)))
               fmt = fmt.replace(regExp, (RegExp.$1.length === 1) ? fmtObj[key] : (('00' + fmtObj[key]).substr(('' + fmtObj[key]).length)))
            }
        }
        return fmt
    }
}

const fmt = "yyyy-MM-dd hh:mm:ss"
const timestamp =  1538148600000
const date = dateFmt(timestamp, fmt) // "2018-09-28 23:30:00"

实例2:计算两个时间戳或Date对象相隔多少天

/*
* 计算time1和time2相隔时间,精确到‘日’
* @param { String | Date } time1
* @param { String | Date } time2
* @return { Number } (time2 - time1) / (24 * 60 * 60 * 1000)
*/
const diffDay = function (time1, time2) {
    // 如果 time1 或者 time2 不是Date对象则将其转换为Date对象
    const time1 = time1 instanceof Date ? time1 : new Date(time1)
    const time2 = time2 instanceof Date ? time2 : new Date(time2)
    
    time1.setHours(0)
    time1.setMinutes(0)
    time1.setSeconds(0)
    time1.setMilliseconds(0)
    time2.setHours(0)
    time2.setMinutes(0)
    time2.setSeconds(0)
    time2.setMilliseconds(0)
    
    /*
    *如果是负数说明 time2 比 time1 早。如 -1,则说明早了一天,即 time1 是今天,则 time2 是昨天。
    *如果是正数说明 time2 比 time1 晚。如1,则说明晚一天,即 time1 是今天,则 time2 是明天。
    */
    return (time2 - time1) / (24 * 60 * 60 * 1000)
}

实例3:将时间戳或者Date对象转换为对应的日期

/*
* 计算 value 的日期,返回值可能为“昨天 00:00”,“今天 00:00”,“明天 00:00”,
* “**月**日 00:00”,“****年**月**日 00:00”,精确到分钟
* @param { String | Date } value
* @return { String } result
*/

const moment = (value) => {
    if(typeof value !== undefined) {
        const today = new Date()
        let result = ''
        value = value instanceof Date ? value : new Date(value)
        // 调用实例2的diffDay()方法
        const diff = diffDay(today, value)
        // 设置日期
        if (diff === -1) {
            result = '昨天'
        } else if (diff === 0) {
            result = '今天'
        } else if (diff === 1) {
            result = '明天'
        } else if (Math.abs(diff) >= 365) {
            result = value.getFullYear() + '年' + (value.getMonth() + 1) + '月' + value.getDate() + '日'
        } else {
            result = (value.getMonth() + 1) + '月' + value.getDate() + '日'
        }
        // 设置小时和分钟
        let hours = value.getHours()
        let minutes = value.getMinutes()
        hours = hours >= 10 ? hours : '0' + hours
        minutes = minutes >= 10 ? minutes : '0' + minutes;
        result += ' ' + hours + ':' + minutes
        
        return result
    } else {
        return false    
    }
}

// 传入时间戳 1538148600000
let result = moment(1538148600000) // "9月28日 23:30" 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 137,150评论 19 139
  • 1 Object 对象 教程:https://wangdoc.com/javascript/stdlib/obje...
    智勇双全的小六阅读 2,554评论 0 0
  • 朋友开车,碰上警察临检,说他脸色苍白嘴唇发紫有吸毒过量的症状。。。硬要他去做检测,一下午的折腾。最后得出结论⋯“中...
    摸鱼哥阅读 764评论 3 17
  • 我用我的愚钝证明你的聪慧 你用你的苦涩征服我的味蕾 你说:“不喜欢做没有意义的事情”。 可我懒得活动,总是处在没有...
    孤风炫尘阅读 255评论 0 0

友情链接更多精彩内容