How to format a date string in React Native?

Sometimes, we want to format a date string in React Native.

In this article, we’ll look at how to format a date string in React Native.

How to format a date string in React Native?

To format a date string in React Native, we can use moment.js.

For instance, we write:

import * as React from 'react';
import { View, Text } from 'react-native';
import Constants from 'expo-constants';
import AssetExample from './components/AssetExample';
import { Card } from 'react-native-paper';
import moment from 'moment';

export default function App() {
  return (
    <View>
      <Text>{moment(new Date(2022, 1, 1)).format('YYYY-MM-DD')}</Text>
    </View>
  );
}

to call moment with a JavaScript date object to create a moment object with the same date.

Then we call format with a format string to return a date string with the given date.

Therefore, we see 2022-02-01 displayed.

Conclusion

To format a date string in React Native, we can use moment.js.