最近遇到一個(gè)問題谤绳,有一些特殊處理的時(shí)間字符串如果直接使用new Date會(huì)導(dǎo)致輸出Invalid Date的問題,例如
new Date("2021年12月20日") // Invalid Date
因?yàn)檫@里的時(shí)間字符串并不是標(biāo)準(zhǔn)的時(shí)間格式,是一個(gè)特殊處理過的。
我們知道這種特殊的時(shí)間字符串是通過一些自定義函數(shù)或Moment.js加時(shí)間模板來生成的。那我們可不可以用時(shí)間模板反義回Date數(shù)據(jù)呢钱贯?自定義處理這類似的問題估計(jì)會(huì)很復(fù)雜,查找Moment.js的方法侦另,發(fā)現(xiàn)Moment.js可以使用自定義時(shí)間模板來格式化時(shí)間字符串
先安裝Moment
npm install moment --save
利用Moment.js格式化時(shí)間字符串生成Date數(shù)據(jù)
const myDate = moment("2021年12月20日", "YYYY年MM月DD日").format() // 2021-12-20
const newDate = new Date(myDate)
附上Moment.js 的官網(wǎng)鏈接https://momentjs.com/
這里Moment.js可換成Dayjs體積更小功能一樣 https://github.com/iamkun/dayjs