Home > Article > Web Front-end > A brief analysis of timestamp operation methods in JavaScript (with code)
In the previous article "This article explains how to use SVG to draw trend charts in HTML (share the code)", I will introduce how to use SVG to draw trend charts. The following article will give you Everyone knows the method of timestamp operation in js, let's take a look.
Several ways to get timestamp
//第一种 var timestamp = Date.now(); //第二种 var timestamp = new Date().getTime(); //第三种 var timestamp = new Date().valueOf(); //第四种,通过运算 var timestamp = new Date() * 1; //new Date()-0 ,new Date()/1 //第五种 ,通过转换 var timestamp = Date.parse(new Date());
Timestamp operation
var timestamp1 = Date.now(); var timestamp2 = Date.now(); var timediff = (timestamp2 - timestamp1) / 1000; //这里拿到的是毫秒,除以1000 得到秒单位 //天数 var days = parseInt(timediff / 3600 / 24); //小时 var hours = parseInt(timediff / 3600); //分钟 var minutes = parseInt((timediff / 60) % 60); //秒 var seconds = parseInt(timediff % 60);
Countdown example
function getDiff(t1, t2) { var timediff = (t2 - t1) / 1000; //天数 var days = parseInt(timediff / 3600 / 24); //小时 var hours = parseInt((timediff / 3600) % 60); //分钟 var minutes = parseInt((timediff / 60) % 60); //秒 var seconds = parseInt(timediff % 60); return days + "天 " + hours + "时 " + minutes + "分 " + seconds + "秒 "; } var t1 = new Date("2019/2/10 8:03:15"); var t2 = new Date("2019/2/18 7:05:55"); var result = getDiff(t1, t2); console.log(result); //7天 11时 2分 40秒 //开始倒计时 今天离2025年还有多少天 setInterval( () => console.log(getDiff(new Date(), new Date("2025/3/20"))), 1000 );
Recommended learning: JavaScript video tutorial
The above is the detailed content of A brief analysis of timestamp operation methods in JavaScript (with code). For more information, please follow other related articles on the PHP Chinese website!