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

How to convert timestamp to number of days in javascript

青灯夜游
Release: 2023-01-07 11:47:26
Original
10151 people have browsed it

Conversion method: First obtain the timestamp of the current time and the timestamp of the specified date; then subtract the two obtained timestamps to obtain the time difference; finally calculate the "time difference / (1000*3600 *24)" expression value is enough.

How to convert timestamp to number of days in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

JS converts the year, month, day, hour, minute and second string into a timestamp

  var time = Date.parse(new Date("2020-08-31 16:00"));
Copy after login

will output a timestamp representing 2020-08-31 16:00:

1598860800000
Copy after login

Convert timestamp to number of days

Subtract the current time from the deadline to calculate the number of days until the deadline

var d = new Date();
var rangeDateNum = (d.getTime()-time) / (1000*3600*24);
Copy after login

Example: Convert 1598860800000 into days

var time = Date.parse(new Date("2020-08-31 16:00"));
var d = new Date();
var rangeDateNum = (d.getTime()-time) / (1000*3600*24);
console.log(rangeDateNum);
Copy after login

Output results:

371.9680493634259
Copy after login

Extended knowledge: converting timestamp to date

//parseInt()字符串转数字
//new Date()放入时间戳,没有放默认当前时间
this.tableData[i].createTime = this.formatDate(new Date(parseInt(this.tableData[i].createTime)))

// 时间戳转换日期格式
    formatDate(now) {
      var year = now.getFullYear();  //取得4位数的年份
      var month = now.getMonth() + 1;  //取得日期中的月份,其中0表示1月,11表示12月
      var date = now.getDate();      //返回日期月份中的天数(1到31)
      var hour = now.getHours();     //返回日期中的小时数(0到23)
      var minute = now.getMinutes(); //返回日期中的分钟数(0到59)
      var second = now.getSeconds(); //返回日期中的秒数(0到59)
      return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    }
Copy after login

[Recommended learning: javascript advanced tutorial

The above is the detailed content of How to convert timestamp to number of days in javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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