peterleee

Js中的date:

JS获取时间戳:(都是毫秒级时间戳,换成秒时间戳需要/1000)

var timestamp1 = Date.parse(new Date());//只能精确到秒,后面的毫秒用000代替
var timestamp2 = (new Date()).valueOf();
var timestamp3 = new Date().getTime();

将时间戳转换为日期格式:如果是秒级时间戳,需要乘以1000

function timestampToTime(timestamp) {
        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 h = date.getHours() + \':\';
        var m = date.getMinutes() + \':\';
        var s = date.getSeconds();
        return Y+M+D+h+m+s;
}
function getLocalTime(timestamp) {     
   return new Date(parseInt(timestamp) * 1000).toLocaleString().replace(/:\d{1,2}$/,\' \');     
} 

function getLocalTime(timestamp) {     
    return new Date(parseInt(timestamp) * 1000).toLocaleString().substr(0,17)}
 

但我们现在好像都用moment对象:

const timestamp = moment(new Date()).valueOf();
const formattime = moment(timestamp).format(\'YYYY-MM-DD HH:mm:ss\');

具体moment的其他用法

请参考:

https://www.jianshu.com/p/9c10543420de

 

分类:

技术点:

相关文章: