簡體   English   中英

在 React 中將 ISO 日期時間格式轉換為可讀格式

[英]Converting ISO datetime format to readable format in React

我正在從本地主機中的 API 獲取數據。 我得到的日期和時間格式如下

"2021-12-08T13:52:16.043"

我只想刪除時間部分並僅顯示日期。 就像是:

2021-12-08 or 2021/12/08 does not matter.

這是我在 React 中的代碼

{allComments.map(c=> (
                        <div>
                            <p>{c.time.toLocalDateString()}</p>
                        </div>
                    )
                    )}

這是行不通的。 錯誤說toLocalDateString()不是 function。 這是我經過一番研究后發現的。 有人可以幫我寫 function 以及如何使用它嗎?

您需要將日期字符串解析為實際的Date object ,然后調用toLocaleDateString

 const c = { time: '2021-12-08T13:52:16.043' }; console.log(new Date(c.time).toLocaleDateString()); // 12/8/2021

或者:

 const c = { time: '2021-12-08T13:52:16.043' }; console.log(new Date(c.time).toLocaleString('en-US', { year: 'numeric', month: 'numeric', day: 'numeric' })); // 12/8/2021

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM