简体   繁体   English

如何在 React-Native 中格式化 ISO 日期

[英]How to format ISO date in React-Native

I am getting date data in this format from my API:我正在从我的 API 获取这种格式的日期数据:

"2018-12-26T05:00:29"

however I need to display this in the application front end in a different format like this:但是我需要在应用程序前端以不同的格式显示它,如下所示:

"Monday, Nov 26 at 10:00 am"

How can I achieve this in react-native?我怎样才能在本机反应中实现这一点?

Consider using a third-party library like momentjs for advanced date parsing and formatting.考虑使用像momentjs这样的第三方库进行高级日期解析和格式化。 Using moment, you can format the date string as required via the following pattern:使用 moment,您可以通过以下模式根据需要格式化日期字符串

// dddd for full week day, MMM for abreviated month, DD for date, etc
moment(inputDate).format("dddd, MMM DD at HH:mm a")

The momentjs library works well with react-native and can be easily installed by: momentjs 库与 react-native 配合良好,可以通过以下方式轻松安装:

npm install moment --save

and imported into your project:并导入到您的项目中:

import moment from 'moment';

Here's a snippet demonstrating the pattern shown above:这是一个演示上述模式的片段:

 var inputDate = "2018-12-26T05:00:29"; var outputDate = moment(inputDate).format("dddd, MMM DD at HH:mm a"); console.log(outputDate);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>

While Moment.js can resolve this issue quickly, it's however a pretty big library to use for a single use case.虽然Moment.js可以快速解决这个问题,但它是一个非常大的库,可用于单个用例。 I recommend using date-fns instead .我建议改用date-fns It's lite.这是轻的。

I come out of this thanks to https://github.com/date-fns/date-fns/issues/376#issuecomment-353871093 .感谢https://github.com/date-fns/date-fns/issues/376#issuecomment-353871093,我从中脱颖而出。

Despite the solution, I did some perfection on Date Field Symbol.尽管有解决方案,但我在日期字段符号上做了一些完善。 You may need to use dd instead of DD / yyyy instead of YYYY for formatting days of the month / for formatting years.您可能需要使用dd而不是DD / yyyy而不是YYYY来格式化月份的日期/格式化年份。

Read the doc here: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md在此处阅读文档: https : //github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM