我正在使用 MongoDB 存盤資料,在檢索它們時,我想獲取日期并將其轉換為如下所示的內容:
'2022-07-20T10:12:21.054Z'
現在我的約會看起來像這樣:
"Nov. 13, 2022 at 5:51 AM "
因為我是通過 createdAt 鍵直接從 mongo 獲取它的。我怎樣才能做到這一點?
uj5u.com熱心網友回復:
> Try this using moment library you can make any format you want.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>
</head>
<body>
<button type="button" onclick="clickHandler()">
Get Today!
</button>
<script>
function clickHandler() {
alert(moment('2022-07-20T10:12:21.054Z')
.format('MMM. , DD YYYY at h:mm:ss a'))
}
</script>
</body>
</html>
uj5u.com熱心網友回復:
const datetostring = (oldDate) => {
// let oldDate = "Nov. 13, 2022 at 5:51 AM "
// console.log(oldDate);
let oldDateArr = oldDate.toString().split(" ");
let month = oldDateArr[0].replace('.', '')
if (month == "Jan") { month = "01" } else if (month == "Feb") { month = "02" } else if (month == "Mar") { month = "03" } else if (month == "Apr") { month = "04" } else if (month == "May") { month = "05" } else if (month == "Jun") { month = "06" } else if (month == "Jul") { month = "07" } else if (month == "Aug") { month = "08" } else if (month == "Sep") { month = "09" } else if (month == "Oct") { month = "10" } else if (month == "Nov") { month = "11" } else if (month == "Dec") { month = "12" } else { month = "12" }
let join = `${oldDateArr[2]}-${month}-${oldDateArr[1].replace(',', '')}T${oldDateArr[4]}:00.054Z`
return (join);
}
這完美地作業
uj5u.com熱心網友回復:
試試這個:(您可能需要定義您的時區才能做到這一點)
const dateStr = 'Nov. 13, 2022 at 5:51 AM'
const regex = /\.|,|\s|:/g
const dateArray = dateStr.split(regex);
const ampmTo24hr = (hh,mm,ampm) => (
ampm === 'AM' ?
`${hh}:${mm}:00` :
`${parseInt(hh,10) 12}:${mm}:00`
);
const [mmm,,dd,,yyyy,,hh,mm,ampm] = dateArray;
const time = ampmTo24hr(hh,mm,ampm);
console.log(`${yyyy}-${mmm}-${dd} ${time}`)
console.log(new Date(`${yyyy}-${mmm}-${dd} ${time}`))
看起來new Date(`${yyyy}-${mmm}-${dd} ${time}`)可能不支持這種格式,為月份格式匹配構建一個陣列或添加一個開關函式可能是一個選擇:
const dateStr = 'Nov. 13, 2022 at 5:51 AM'
const regex = /\.|,|\s|:/g
const dateArray = dateStr.split(regex);
const getMonth = (str) => {
switch(str.toUpperCase()) {
case 'JAN': return '01';
case 'FEB': return '02';
case 'MAR': return '03';
case 'APL': return '04';
case 'MAY': return '05';
case 'JUN': return '06';
case 'JUL': return '07';
case 'AUG': return '08';
case 'SEP': return '09';
case 'OCT': return '10';
case 'NOV': return '11';
case 'DEC': return '12';
}
}
const ampmTo24hr = (hh,mm,ampm) => (
ampm === 'AM' ?
`${hh}:${mm}:00` :
`${parseInt(hh,10) 12}:${mm}:00`
);
const [mmm,,dd,,yyyy,,hh,mm,ampm] = dateArray;
const time = ampmTo24hr(hh,mm,ampm);
console.log(new Date(`${yyyy}-${getMonth(mmm)}-${dd} ${time}`))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/532265.html
上一篇:如何使用python從YouTube時間戳中獲取開始時間、結束時間(以秒為單位)?
下一篇:Python子字串正則運算式提取
