習慣沉默2017-07-05 10:52:156楼
Edit: 对提出的 case 做简单转换:
const date str = '20170523'
const result = new Date()
result.setFullYear(parseInt(str.substr(0, 4)))
result.setMonth(parseInt(str.substr(4, 2)) - 1)
result.setDate(parseInt(str.substr(6, 2)))
// 函数定义见下
getDateFromTimestamp(result.getTime())
一个简单的实现如下:
// 1495517932472 毫秒级时间戳
const date = new Date().getTime()
function formatMonth (num) {
return [
'01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'
][num]
}
function getDateFromTimestamp (ts) {
const date = new Date(ts)
const YYYY = date.getFullYear()
const MM = formatMonth(date.getMonth())
const DD = date.getDate()
return `${YYYY}-${MM}-${DD}`
}
// 2017-05-23
console.log(getDateFromTimestamp(date))