[英]React native moment formatted date in invalid
I have the following code in my RN application.我的 RN 应用程序中有以下代码。
getFormattedDate = (date) => {
const formattedDate = moment(new Date(date)).format('MMMM, DD YYYY');
return { date: formattedDate };
}
When I run this on the emulator, the formatted date is displayed properly.当我在模拟器上运行它时,格式化的日期显示正确。 But when I run this on device, it says, invalid date.但是当我在设备上运行它时,它说,无效日期。 What am I doing wrong here?我在这里做错了什么?
From your comments, I assume that the date
parameter is a string.根据您的评论,我假设date
参数是一个字符串。 If you want to create a new moment from a string, you have to pass the date format.如果要从字符串创建新时刻,则必须传递日期格式。 The newly created moment can then be formatted with .format
to get a string again.然后可以使用.format
格式化新创建的时刻以再次获取字符串。
Change:改变:
const formattedDate = moment(new Date(date)).format('MMMM, DD YYYY');
To:到:
const formattedDate = moment(date,"MMM, DD YYYY").format("MMMM, DD YYYY");
Here you can find more details about the string format .在这里您可以找到有关字符串格式的更多详细信息。
npm install date-fns --save npm install date-fns --save
import { format } from 'date-fns'从'date-fns'导入{格式}
format(new Date(), 'MMMM, DD YYYY')格式(新日期(),'MMMM,DD YYYY')
Moment is 150x slower than new Date . Moment 比 new Date 慢 150 倍。 Please try it like this if you want to use this code working.如果您想使用此代码工作,请像这样尝试。
getFormattedDate = async (date) => {
const formattedDate = await moment(new Date(date)).format('MMMM,DD YYYY');
return { date: formattedDate };
}
you can read it here for more details https://github.com/moment/moment/issues/731你可以在这里阅读更多细节https://github.com/moment/moment/issues/731
I would suggest avoid using moment because of the performance.由于性能,我建议避免使用时刻。 Use new Date () and then fetch the day , month and year and change into suitable format by joining the strings as you want.使用 new Date () 然后获取日、月和年,并通过根据需要加入字符串来更改为合适的格式。 Use only Date library.仅使用日期库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.