Home > Web Front-end > JS Tutorial > body text

A brief analysis of timestamp operation methods in JavaScript (with code)

奋力向前
Release: 2021-08-26 14:01:07
forward
3040 people have browsed it

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.

A brief analysis of timestamp operation methods in JavaScript (with code)

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());
Copy after login

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);
Copy after login

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
);
Copy after login

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!

Related labels:
js
source:chuchur.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template