shira
shira

Reputation: 394

React Native: How to convert date format?

How to convert the date format ? In my example, I now get the date like this: 2020-09-01 and I want it to be 01/09/2020. How should I do it ?

             <Text
                style={{
                  fontSize: 20,
                  fontWeight: 'bold',
                  color: '#368fc7',
                  paddingLeft: 10,
                }}
              >
                {date2.toISOString().slice(0, 10)}
              </Text>

Upvotes: 1

Views: 6409

Answers (3)

Daniel Givoni
Daniel Givoni

Reputation: 743

You can use moment.js package - https://momentjs.com/

 import moment from 'moment';

         <Text
            style={{
              fontSize: 20,
              fontWeight: 'bold',
              color: '#368fc7',
              paddingLeft: 10,
            }}
          >
            {moment(date2).format('DD/MM/YYYY')}
          </Text>

Upvotes: 1

kshetline
kshetline

Reputation: 13672

If you want to be flexible and adapt to different locale date styles, this will do the trick:

new Date().toLocaleDateString().replace(/\b(\d)\b/g, '0$1')

Most of the formatting you want is built into JavaScript, but it needs some help with a regex like this to force leading zeros.

Upvotes: 1

user14080122
user14080122

Reputation:

const dateY = new Date();
let YDAY= `${dateY.getDate()}/${dateY.getMonth() + 1}/${dateY.getFullYear()}`
console.log(YDAY);

Try this, and let me know!

Upvotes: 3

Related Questions