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?

3
  • You can use libraries like dayjs to convert date. Commented Oct 14, 2021 at 17:27
  • is there a way using vanilla js? Commented Oct 14, 2021 at 17:27
  • Check this stackoverflow.com/questions/27480262/… Commented Oct 14, 2021 at 17:28

4 Answers 4

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)

Sign up to request clarification or add additional context in comments.

Comments

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')

1 Comment

Great addition to mention a library. It would be helpful to include the full npm install command,
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);

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.