2

I am trying to format my date in React/ typescript project, however the data is from an api, so I can map over the data and display it but how do I convert it to a format like '22 June 2021'?

The data from the api is in format:

{
   "title": 'First',
   "time": "2020-07-22T13:22:10.2566789+00:00", 
}

Then I am binding to the template as {data.time}

Any idea's?

Sole
  • 3,100
  • 14
  • 58
  • 112

4 Answers4

3

Yes, it is a simple way to achieve that

const date = new Date("2020-07-22T13:22:10.2566789+00:00")
const formattedDate = date.toLocaleDateString("en-GB", {
  day: "numeric",
  month: "long",
  year: "numeric"
})

console.log(formattedDate)
2

PackageName: npm i moment

Install the moment npm. "moment" is an npm package. After installation import the package import moment from 'moment' Next, Convert the data like this:

"time": "2020-07-22T13:22:10.2566789+00:00"
moment(time).format('DD/MM/YYYY HH:mm')
Micro Kumar
  • 167
  • 1
  • 12
0

For Example, if your code is like this:

var objName = {
   "title": 'First',
   "time": "2020-07-22T13:22:10.2566789+00:00", 
}

This is how you can implement the new Time Format (Dont forget to npm install and import moment.js)

let formattedTime = moment(objName.time).format('DD/MM/YYYY HH:mm');

console.log(formattedTime);
Adith Ls
  • 11
  • 2
0

DateFns it is a light library, so I can recommend it.

import format from 'date-fns/format'

const formattedDate = format(
  new Date('2020-07-22T13:22:10.2566789+00:00'),
  'dd MMMM yyyy'
)

console.log(formattedDate)