曹耘豪的博客

JS日期格式化

  1. 原生方式
  2. 引入momentjs

原生方式

1
2
3
4
5
6
7
8
9
10
11
12
13
function formatDateTime(date) {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return `${pad(year, 4)}-${pad(month)}-${pad(day)} ${pad(hour)}:${pad(minute)}:${pad(second)}`
}

function pad(value, total = 2, str = '0') {
return value.toString().padStart(total, str)
}
老版本js
1
2
3
4
5
6
7
8
9
10
function formatDateTime(date) {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()

return year.toString().padStart(4, '0') + '-' + month.toString().padStart(2, '0') + '-' + day.toString().padStart(2, '0') + ' ' + hour.toString().padStart(2, '0') + ':' + minute.toString().padStart(2, '0') + ':' + second.toString().padStart(2, '0')
}

引入momentjs

   /