js获取时间戳的三种方式

CreateTime--2018年5月23日08:44:10

获取时间戳

// 方式一:推荐使用
var timestamp=new Date().getTime();
console.log(timestamp);
// 方式二
timestamp = (new Date()).valueOf();
console.log(timestamp);
// 方式三
timestamp = Date.parse(new Date());
console.log(timestamp);

效果展示

时间戳转日期

/**
 * 时间戳转日期
 * @param timestamp
 * 数值类型时间戳,不能是字符串类型数字
 * @return {string}
 */
function timestampToDateTime(timestamp) {
    var date = new Date(timestamp);
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate()<10 ? '0'+date.getDate() : date.getDate())+' ';
    var h = (date.getHours()<10 ? '0'+date.getHours() : date.getHours()) + ':';
    var m = (date.getMinutes()<10 ? '0'+date.getMinutes() : date.getMinutes()) + ':';
    var s = date.getSeconds()<10 ? '0'+date.getSeconds() : date.getSeconds();
    return Y + M + D + h + m + s;
}

示例:

 

写在最后

  哪位大佬如若发现文章存在纰漏之处或需要补充更多内容,欢迎留言!!!

 相关推荐:

posted @ 2018-05-23 08:47  Marydon  阅读(1851)  评论(0编辑  收藏  举报