1 var curDate = new Date();
2 var preDate = new Date(curDate.getTime() - 24 60 60 1000); //The previous day
3 var nextDate = new Date(curDate.getTime() + 24 60 60 1000) ; //the day after
Let's summarize the mutual conversion between timestamp and date format in js:
1. Convert timestamp to date format:
function timestampToTime(timestamp) {
var date = new Date(timestamp * 1000); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
let Y = date.getFullYear() + '-' ;
let M = (date.getMonth()+1 < 10 ? '0' +(date.getMonth()+1) : date.getMonth()+1) + '-' ;
let D = date.getDate() + ' ' ;
let h = date.getHours() + ':' ;
let m = date.getMinutes() + ':' ;
let s = date.getSeconds();
return Y+M+D+h+m+s;
}
timestampToTime(1403058804);
console.log(timestampToTime(1403058804)); //2014-06-18 10:33:24
- Note: If it is a Unix timestamp, remember to multiply it by 1000. For example: The timestamp obtained by the PHP function time() must be multiplied by 1000.
2. Convert the date format to a timestamp:
var date = new Date( '2014-04-23 18:55:49:123' );
// 有三种方式获取
var time1 = date.getTime();
var time2 = date.valueOf();
var time3 = Date.parse(date);
console.log(time1); //1398250549123
console.log(time2); //1398250549123
console.log(time3); //1398250549000
- Note
The difference between the above three acquisition methods:
The first and second types: will be accurate to milliseconds
The third type: it can only be accurate to the second, and the millisecond is replaced by 000
The above three output results can observe the difference
- Note: The Unix timestamp can be obtained by dividing the obtained timestamp by 1000, which can be passed to the background to obtain it.
Reprinted at: https://www.cnblogs.com/thelongmarch/p/7649430.html