Home > Web Front-end > JS Tutorial > Common ways to get time in js (code)

Common ways to get time in js (code)

不言
Release: 2018-10-16 13:44:32
forward
1982 people have browsed it

The content of this article is about the common methods (code) of obtaining time in js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Get the timestamp of the current time

 //第一种方法(精确到秒)
 var timestamp = Date.parse(new Date());

 //第二种方法(精确到毫秒)
 var timestamp = (new Date()).valueOf();

 //第三种方法(精确到毫秒)
 var timestamp=new Date().getTime();
Copy after login

2. Convert the timestamp to the specified date format

  //第一种
  function getLocalTime(nS) {
    return new Date(parseInt(nS)).toLocaleString().replace(/:\d{1,2}$/, ' ');
  }
  var nowTime = getLocalTime(timestamp);  //  2018/10/15 下午9:45

  //第二种
  function getLocalTime1(nS) {
    return new Date(parseInt(nS)).toLocaleString().substr(0, 17)
  }
  var nowTime = getLocalTime1(timestamp); // 2018/10/15 下午9:53

  //第三种
   function getLocalTime2(nS) {
    return new Date(parseInt(nS)).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
  }
  let nowTime1 = getLocalTime2(timestamp); //    2018/10/15 下午9:53:10
Copy after login

3. Get the timestamp of 0 o'clock today

let getZeroTimestamp = new Date(new Date().toLocaleDateString()).getTime();
Copy after login

The above is the detailed content of Common ways to get time in js (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template