创建传递日期格式 mmddyyyy 的日期对象
Create Date object passing a date format of mmddyyyy
我正在尝试创建格式为 'mmddyyyy'
的日期。我注意到我可以传递一个四位数的字符串,但是当我使用上面的格式时,它说无效日期。我怎样才能用纯 js 解决这个问题?
let dateString = '01012022'
let d = new Date(dateString)
也许你想要这样的东西
let dateString = '01012022'
let [match, dd, mm, yyyy] = dateString.match(/(\d{2})(\d{2})(\d{4})/)
// iso format
let d = new Date(`${yyyy}${mm}${dd}`)
似乎您必须将字符串拆分成多个部分然后使用通用的 Date() 构造函数将日、月和年分开
//Your string with date
let dateString = '01012022';
//extracting 2 first numbers as m (month), 2 second as d (day) and the last 4 as y (year)
let {d,m,y} = /(?<m>\d{2})(?<d>\d{2})(?<y>\d{4})/.exec(dateString).groups;
//then create new date using constructor
let date = new Date(y,m,d);
我正在尝试创建格式为 'mmddyyyy'
的日期。我注意到我可以传递一个四位数的字符串,但是当我使用上面的格式时,它说无效日期。我怎样才能用纯 js 解决这个问题?
let dateString = '01012022'
let d = new Date(dateString)
也许你想要这样的东西
let dateString = '01012022'
let [match, dd, mm, yyyy] = dateString.match(/(\d{2})(\d{2})(\d{4})/)
// iso format
let d = new Date(`${yyyy}${mm}${dd}`)
似乎您必须将字符串拆分成多个部分然后使用通用的 Date() 构造函数将日、月和年分开
//Your string with date
let dateString = '01012022';
//extracting 2 first numbers as m (month), 2 second as d (day) and the last 4 as y (year)
let {d,m,y} = /(?<m>\d{2})(?<d>\d{2})(?<y>\d{4})/.exec(dateString).groups;
//then create new date using constructor
let date = new Date(y,m,d);