我正在嘗試在 React/typescript 專案中格式化我的日期,但是資料來自 api,因此我可以映射資料并顯示它,但是如何將其轉換為諸如“2021 年 6 月 22 日”之類的格式?
來自 api 的資料格式為:
{
"title": 'First',
"time": "2020-07-22T13:22:10.2566789 00:00",
}
然后我系結到模板 {data.time}
有任何想法嗎?
uj5u.com熱心網友回復:
是的,這是實作這一目標的簡單方法
const date = new Date("2020-07-22T13:22:10.2566789 00:00")
const formattedDate = date.toLocaleDateString("en-GB", {
day: "numeric",
month: "long",
year: "numeric"
})
console.log(formattedDate)
uj5u.com熱心網友回復:
安裝時刻 npm。“時刻”是一個 npm 包。安裝后從'時刻'匯入包匯入時刻接下來,像這樣轉換資料:
"time": "2020-07-22T13:22:10.2566789 00:00"
moment(time).format('DD/MM/YYYY HH:mm')
uj5u.com熱心網友回復:
也許這就是你要找的
const res = {
"time": "2020-07-22T13:22:10.2566789 00:00",
}
const s = res.time.split(/\D/g) //split in non-digit characters
const date = new Date(s[0], s[1] - 1, s[2])
const month = date.toLocaleString('default',{month:'long'})
console.log(s[2], month, s[0])
uj5u.com熱心網友回復:
例如,如果您的代碼是這樣的:
var objName = {
"title": 'First',
"time": "2020-07-22T13:22:10.2566789 00:00",
}
這是實作新時間格式的方法(不要忘記 npm install 并匯入 moment.js)
let formattedTime = moment(objName.time).format('DD/MM/YYYY HH:mm');
console.log(formattedTime);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/315097.html
