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?
CodePudding user response:
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)
CodePudding user response:
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')
CodePudding user response:
maybe that is what you are looking for
const res = {
"time": "2020-07-22T13:22:10.2566789 00:00",
}
const s = res.time.split(/\D/g) //split in non-digit characters
const date = new Date(s[0], s[1] - 1, s[2])
const month = date.toLocaleString('default',{month:'long'})
console.log(s[2], month, s[0])
CodePudding user response:
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);