js获取指定时间戳

JavaScript016

js获取指定时间戳,第1张

第一种方法:

var timestamp = Date.parse(new Date())

结果:1280977330000

第二种方法:

var timestamp = (new Date()).valueOf()

结果:1280977330748

第三种方法:

var timestamp=new Date().getTime();

结果:1280977330748

第一种:获取的时间戳是把毫秒改成000显示,

第二种和第三种是获取了毫秒的时间戳。

在js中,可以对两个时间戳进行相减,使用if语句判断结果,从而实现时间戳的比较。具体步骤如下:

1、在test.html文件内,命名为test.html,用于讲解js时间戳怎么比较。

2、在test.html文件内,在js标签内创建一个pan()函数,函数有两个参数,分别st1,st2。

3、在pan()函数内,分别将两个时间使用new Date()转换为时间对象,保存在t1,t2变量中。

4、在pan()函数内,将两个时间对象分别利用getTime()方法转换为时间戳,分别保存在变量tt1,tt2变量中。

5、在pan()函数内,将两个时间戳相减,差值保存在res变量中。

6、在pan()函数内,使用if语句对res进行判断,如果res等于0,提示“两个时间相等”,如果res大于0,提示“t1时间大于t2时间”,如果不符合上面两种情况,则提示“t2时间大于t1时间”。

7、在pan()函数外,创建两个时间变量,并调用pan()函数进行判断。

8、在浏览器打开test.html文件,查看判断的结果。

var formatTime = function(time = new Date(), format) {

    const TOTOW = e => `0${e}`.substr(-2) // 转成2位的格式  1 => 01

    const date = new Date(time)

    const yyyy = date.getFullYear()

    const MM = TOTOW(date.getMonth() + 1)

    const dd = TOTOW(date.getDate())

    const hh = TOTOW(date.getHours())

    const mm = TOTOW(date.getMinutes())

    const ss = TOTOW(date.getSeconds())

    let result

    if (format) {

      result = format.replace(/yyyy/i, yyyy).replace(/MM/, MM).replace(/dd/i, dd).replace(/hh/i, hh).replace(/mm/, mm).replace(/ss/i, ss)

    } else {

      result = `${yyyy}-${MM}-${dd} ${hh}:${mm}:${ss}`

    }

    return result

}

setInterval(() => {

let now = formatTime(new Date(), 'yyyy年MM月dd日 hh时mm分ss秒') // 月份必须是大写MM,分钟必须是小写mm,其他大小写都行

document.body.innerText = now

}, 1000)