JS 格式化时间

想得到format后的时间?现在不用再get年月日时分秒了,三步搞定,貌似有缺陷,如果是下午的小时得到的不大对。

var temp = new Date();
var regex = ///g;
(temp.toLocaleDateString() + ' ' + temp.toLocaleTimeString().slice(2)).replace(regex,'-');

// "2015-5-7 9:04:10"

想将一个标准的时间对象转换为unix时间戳?valueOf搞定之。

(new Date).valueOf();

// 1431004132641

许多朋友还提醒了这样可以快速得到时间戳

+new Date
// 1431004132641

日常工作中还是推荐 moment.js,不过 moment 可能会遇到 ts 的麻烦。

import moment from 'moment';

const ts = new Date();
moment(ts).format('YYYY-MM-DD HH:mm:ss')
moment(ts).format('x') // 时间戳

当然也有全面一些的函数

var parseTime = function (value, format) {
    if (!value || (+value) !== (+value)) {
        return value;
    }
    if (value.toString().length === 10) {
        value = (+value) * 1000;
    }
    var date = new Date(value);
    var o = {
        'M+': date.getMonth() + 1, //month
        'D+': date.getDate(), //day
        'h+': date.getHours(), //hour
        'm+': date.getMinutes(), //minute
        's+': date.getSeconds(), //second
        'S': date.getMilliseconds() //millisecond
    };

    if (/(Y+)/.test(format)) {
        format = format.replace(RegExp.$1,
            date.getFullYear().toString().substr(4 - RegExp.$1.length));
    }

    for(var k in o) {
        if (new RegExp('('+ k +')').test(format)) {
            format = format.replace(RegExp.$1,
                RegExp.$1.length == 1 ? o[k] : ('00'+ o[k]).substr((''+ o[k]).length));
        }
    }
    return format;
}
原文地址:https://www.cnblogs.com/everlose/p/12501175.html