最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React native moment formatted date in invalid - Stack Overflow

programmeradmin2浏览0评论

I have the following code in my RN application.

  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?

I have the following code in my RN application.

  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?

Share Improve this question asked Jun 20, 2019 at 6:52 Shashika VirajhShashika Virajh 9,46720 gold badges65 silver badges112 bronze badges 2
  • 1 How does date look like? Is it an ISO date string? – Matei Radu Commented Jun 20, 2019 at 6:54
  • This is the format. => June, 20 2019 – Shashika Virajh Commented Jun 20, 2019 at 7:38
Add a ment  | 

3 Answers 3

Reset to default 5

From your ments, I assume that the date parameter is a string. 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.

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

import { format } from 'date-fns'

format(new Date(), 'MMMM, DD YYYY')

Check this document

Moment is 150x slower than new Date . 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./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. Use only Date library.

发布评论

评论列表(0)

  1. 暂无评论