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.
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"));
will output a timestamp representing 2020-08-31 16:00:
1598860800000
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);
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);
Output results:
371.9680493634259
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; }
[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!