js时间格式化怎么去优化?

splitDate() {
      const createStartTime = this.orderDate[0]
      const createEndTime = this.orderDate[1]
      const createStartMonth = (createStartTime.getMonth() + 1) < 10 ? '0' + (createStartTime.getMonth() + 1) : createStartTime.getMonth() + 1
      const createEndMonth = (createEndTime.getMonth() + 1) < 10 ? '0' + (createEndTime.getMonth() + 1) : createEndTime.getMonth() + 1
      const createStartDate = createStartTime.getDate() < 10 ? '0' + (createStartTime.getDate()) : createStartTime.getDate()
      const createEndDate = createEndTime.getDate() < 10 ? '0' + (createEndTime.getDate()) : createEndTime.getDate()
      const createStartHours = createStartTime.getHours() < 10 ? '0' + createStartTime.getHours() : createStartTime.getHours()
      const createEndHours = createEndTime.getHours() < 10 ? '0' + createEndTime.getHours(): createEndTime.getHours()
      const createStartMinutes = createStartTime.getMinutes() < 10 ? '0' + createStartTime.getMinutes() : createStartTime.getMinutes()
      const createEndMinutes = createEndTime.getMinutes() < 10 ? '0' + createEndTime.getMinutes(): createEndTime.getMinutes()
      const createStartSeconds = createStartTime.getSeconds() < 10 ? '0' + createStartTime.getSeconds() : createStartTime.getSeconds()
      const createEndSeconds = createEndTime.getSeconds() < 10 ? '0' + createEndTime.getSeconds(): createEndTime.getSeconds()
      this.orderForm.createStartTime = createStartTime.getFullYear() + '-' + createStartMonth + '-' + createStartDate + ' ' + createStartHours + ':' + createStartMinutes + ':' + createStartSeconds
      this.orderForm.createEndTime = createEndTime.getFullYear() + '-' + createEndMonth + '-' + createEndDate + ' ' + createEndHours + ':' + createEndMinutes + ':' + createEndSeconds
    }

我想把一个标准时间转换为2019-01-01 09:01这样的格式,当月份和时分秒小于10的时候前面补上0,于是用了上面的三元来判断,一个是开始时间,一个是结束时间,但是写完发现好臃肿,请问一下,这样的话如何优化使得代码更精简?

阅读 4.6k
7 个回答
Date.prototype.toFormattedString = function (format) {
    const O = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "H+": this.getHours(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "f": this.getMilliseconds()
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (let 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;
};

各种格式,都能胜任:

let date = new Date();

date.toFormattedString('yyyy-MM-dd HH:mm:ss'); // 2019-11-07 08:52:13
date.toFormattedString('yy/MM/dd'); // 19/01/01
date.toFormattedString('M月d日'); // 11月7日
date.toFormattedString('HH:mm:ss'); // 08:52:13
date.toFormattedString('m分,s秒'); // 52分,13秒
https://github.com/fudiwei/sk...

个人建议可以用插件来做。dayjs moment都可以处理。个人推荐dayjs,dayjs所占的内存比moment小

之前在手机上贴的答案,格式乱了,现在格式刷刷了一下。
自己项目里写的一个转换函数,传入一个时间戳(单位s)和时间格式,返回时间字符串。

function formatTime(timestamp, format = 'yyyy-MM-dd HH:mm') {
  const formatNum = num => String(num).padStart(2, '0')
  const date = new Date(timestamp * 1000)
  return format.replace(/yyyy/g, date.getFullYear())
    .replace(/MM/g, formatNum(date.getMonth() + 1))
    .replace(/dd/g, formatNum(date.getDate()))
    .replace(/HH/g, formatNum(date.getHours()))
    .replace(/mm/g, formatNum(date.getMinutes()))
    .replace(/ss/g, formatNum(date.getSeconds()))
    .replace(/SSS/g, formatNum(date.getMilliseconds()))
}

想要什么格式都可以随意定制:
image.png

写一个函数专门处理呀,然后调用就行了,就不用一个一个写了

str2(num){
    num = '00' + num
    return num.substr(num.length - 2, 2)
},
dateFormat(date){
    let Y = date.getFullYear()
    let M = date.getMonth() + 1
    let D = date.getDate()
    let h = date.getHours()
    let m = date.getMinutes()
    return Y + '-' + this.str2(M) + '-' + this.str2(D) + ' ' + this.str2(h) + ':' + this.str2(m)
},
splitDate(){
    this.orderForm.createStartTime = this.dateFormat(this.orderDate[0])
    this.orderForm.createEndTime = this.dateFormat(this.orderDate[1])
}

专业的事就请专业的插件来做了。
比如 moment.js

推荐问题
宣传栏