gpt4 book ai didi

javascript - 将 Aug 19th 2018 转换为 08-19/2018-Javascript

转载 作者:行者123 更新时间:2023-11-28 11:20:49 24 4
gpt4 key购买 nike

我想将日期字符串“Aug 19th 2018”转换为“mm-dd-yyyy”格式(不使用 moment.js) 我用过

d = new Date("Aug 19th 2018")

它会导致 NaN,因为它无法解析“19th”。如何实现这一目标?

最佳答案

创建自定义函数并将日期转换为所需格式

let dt = "Aug 19th 2018";


function convertDate(dt) {
let newFormat = "";
// a mapping of month name and numerical value
let monthMapping = {
jan:'01',
feb: '02',
mar: '03',
april: '04',
may: '05',
june: '06',
july: '07',
aug: '08',
sept: '09',
oct: '10',
nov: '11',
dec: '12'
}
// split the input string into three pieces
let splitDt = dt.split(" ");
// from the first piece get the numerical month value from the above obhect
let getMonth = monthMapping[splitDt[0].toLowerCase()];
let date = parseInt(splitDt[1], 10)
let year = splitDt[2]
return `${getMonth}-${date}-${year}`
}

console.log(convertDate(dt))

关于javascript - 将 Aug 19th 2018 转换为 08-19/2018-Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51074691/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com