简体   繁体   English

在 React 中将 ISO 日期时间格式转换为可读格式

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

I am fetching data from an API in localhost.我正在从本地主机中的 API 获取数据。 The date & time I get are in the following format我得到的日期和时间格式如下

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

I just want to remove the time part and show only the date.我只想删除时间部分并仅显示日期。 Something like:就像是:

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

this is my code in React这是我在 React 中的代码

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

This is not working.这是行不通的。 The error says toLocalDateString() is not a function.错误说toLocalDateString()不是 function。 Thats what I found after some research.这是我经过一番研究后发现的。 Could someone please help me with the write function and how to use it?有人可以帮我写 function 以及如何使用它吗?

You will need to parse your date string into an actual Date object and then call toLocaleDateString .您需要将日期字符串解析为实际的Date object ,然后调用toLocaleDateString

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

Alternatively:或者:

 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