Js-日期时间戳互转,时间比较(不用插件)

小tips:

new Date()这个东西的意义,他是用来格式化数据的,然后我们才能用js提供的各种方法,以这个思路去看下面的内容

日期转–>时间戳

当前时间转时间戳:let a = new Date().getTime()
目标时间转时间戳:
let a = new Date(‘2021-08-31 13:05:05’).getTime()
let a = new Date(‘2021/08/31 13:05:05’).getTime()

在这里插入图片描述
getTime()是毫秒级别的。Date.parse()是秒级别的。后者写法麻烦,不建议了
在这里插入图片描述

时间戳转–>日期

let a = new Date(1630386359000)
年:a.getFullYear()
月:a.getMonth()+1
日:a.getDate()
时:a.getHours()
分:a.getMinutes()
秒:a.getSeconds() //都是不带0的
~~~~~~~~~~~ 一键复制即用的代码在文末 ~~~~~~~~~~~~~~~~~~~~~

时间比较、判断

比较肯定是用时间戳比较是最最最稳的,转时间戳就好了
7天的时间戳是:1000*60*60*24*7
比如大于7天时,显示红色,这时候就好判断多了。

快速获得当前日期(多用于导出文件的时间)

let a = new Date().toLocaleDateString() —— 2021/3/8(不补0的)

时间戳转日期的代码

//传入时间戳
		gettime(val) {
    
    
            let date=new Date(val)
            let y=date.getFullYear()
            let m=date.getMonth()+1
            let d=date.getDate()
            let h=date.getHours() 
            let mu=date.getMinutes()
            let s=date.getSeconds()
            let time= y+'-'+m+'-'+d+' '+ this.add0(h) +':'+this.add0(mu)+':'+this.add0(s)
            return time
        },
        add0(m) {
    
    
            return m<10?'0'+m:m     //补0
        },
console.log(this.gettime(1630386359000))       //2021-8-31 13:05:59

猜你喜欢

转载自blog.csdn.net/weixin_45629623/article/details/114543286