JS date and time stamp format conversion

1. The conversion date stamp format:

var date = new Date('2020-03-05 09:00:00');
// 有三种方式获取
var time1 = date.getTime();

var time2 = date.valueOf();

var time3 = Date.parse(date);

console.log(time1);//1583370000000

console.log(time2);//1583370000000

console.log(time3);//1583370000000

Note: Use this Apple phone because there are spaces in the middle cause results to date is NaN, the date can be divided and then converted

var str='2018-06-08 18:00:00' ;

var time=new Date(str.split(" ")).getTime();

2. timestamp into a Date format:

function timestampToTime(timestamp) {
    var  date = new Date(timestamp);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
        // var  date = new Date(timestamp * 1000);//时间戳为10位需*1000,时间戳为13位的话不需乘1000

    var Y = date.getFullYear() + '-';

    var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
         // var D = date.getDate() + ' ';
    var D = (date.getDate() < 10 ? '0'+(date.getDate()) : date.getDate()) + ' ';
         // var h = date.getHours() + ':';
    var h = (date.getHours() < 10 ? '0'+(date.getHours()) : date.getHours()) + ':';
         // var m = date.getMinutes() + ':';
    var m = (date.getMinutes() < 10 ? '0'+(date.getMinutes()) : date.getMinutes()) + ':';
         // var s = date.getSeconds();
    var s = (date.getSeconds() < 10 ? '0'+(date.getSeconds()) : date.getSeconds());

  return Y+M+D+h+m+s;
}

timestampToTime(1583370000000);

console.log(timestampToTime(1583370000000));  // 2020-03-05 09:00:00

Guess you like

Origin www.cnblogs.com/nayek/p/12421146.html