Arash Rabiee
Arash Rabiee

Reputation: 1099

using moment in react native

when I import moment like:

import * as moment from 'moment';

I get the following error

moment is not a function.

When import it like:

import moment from 'moment';

I get the following error:

External module 'moment' has no default export

What is the best way to add moment to react native?

By the way I added moment by this command: npm install --save moment

I also used toLocaleDateString() before, it works on IOs but it doesn't work properly on android so I have to use moment.

Upvotes: 2

Views: 10549

Answers (4)

Omar bakhsh
Omar bakhsh

Reputation: 1062

1- first, install :

npm i moment 

2- second import :

import moment from "moment";

3- then use and get the moment date :

const [currentDate, setCurrentDate] = useState('');

useEffect(() => {   
        
    // get current time 

     var date = moment().utcOffset('+03:00').format('YYYY-MM-DD');

    // or get time ' hh:mm:ss a'

    setCurrentDate(date); 
 }, []);

4- finely use :

<Text style={styles.txtcurentDate}>Current Date:{currentDate}</Text >

Upvotes: 3

SDushan
SDushan

Reputation: 4631

Since you are using expo, import moment as

let moment = require('moment');

Hope this helps you. Feel free for doubts.

Upvotes: 1

Khanh Le Tran
Khanh Le Tran

Reputation: 900

check node_module and package.json that you already have moment package. If you have all of these just remove node_modules and install all packages again.

Upvotes: 1

Adilp
Adilp

Reputation: 459

import moment from "moment";

You have that right. If you are having problems with npm try running npm install in the root directory.

Upvotes: 1

Related Questions