JavaScript Answers React Native Answers

How to format a date string in React Native?

Spread the love

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 (
      <Text>{moment(new Date(2022, 1, 1)).format('YYYY-MM-DD')}</Text>

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.