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

I have the following code in my RN application.getFormattedDate = (date) => {const formattedDate = m

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745580415a4634222.html

相关推荐

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

    I have the following code in my RN application.getFormattedDate = (date) => {const formattedDate = m

    12小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信