1

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>
colourCoder
  • 1,227
  • 2
  • 7
  • 17
shira
  • 344
  • 1
  • 8
  • I am not into react-native but i would assume there is no special way different from how you do it in javascript. See https://stackoverflow.com/questions/3552461/ – kai Sep 01 '20 at 09:09
  • Try `moment` library for react native. It is very useful in any type of formatting in `react` and `javascript` – Bhupesh Sep 01 '20 at 09:31

3 Answers3

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

Try this, and let me know!

1

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>
Daniel Givoni
  • 350
  • 3
  • 10
0

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.

kshetline
  • 8,496
  • 4
  • 19
  • 44
  • its give me 09/01/20 and i want it wil be 01/09/20 – shira Sep 01 '20 at 09:42
  • That was actually the point of this option, in case you wanted the native locale, rather than forcing a particular style. This: `new Date().toLocaleDateString('fr').replace(/\b(\d)\b/g, '0$1')` will give you 01/09/2020 because date-then-month is what's used in French (and, of course, many other languages). – kshetline Sep 01 '20 at 09:47
  • its still gives me 09/01/20 and i want it will be 01/09/20 .. – shira Sep 01 '20 at 09:50
  • Even with `'fr'` it's still 09/01/20!? At any rate, if all you ever, ever want is 01/09/20, don't worry about this post then. Like I said, the point was for being more flexible IF you needed that. – kshetline Sep 01 '20 at 16:16