You can create a new instance of the class Date
passing to string date to constructor and use the instance methods to create the formatted date.
Note: To string passed as first argument for the class constructor must follow a pattern. For more information, see here.
After creating the instance, use the methods getDate
, getMonth
and getFullYear
to access the day, month and year respectively. Something like this:
const date = new Date('2018-07-19T22:07:00.000-03:00')
const day = date.getDate().toString().padStart(2, '0')
const month = (date.getMonth() + 1).toString().padStart(2, '0')
const year = date.getFullYear()
const formatted = `${day}/${month}/${year}`
console.log(formatted)
Some remarks regarding the code:
- I created a function
padNum
to add a 0
in days or months without two digits.
- We must add one to the number returned in
getMonth
(line 9), since this method returns the months starting at index 0:
- January
0
;
- Feb
1
;
...
;
- December
11
.
Take a look here: https://answall.com/questions/6526/comorformatar-data-no-javascript
– Magno
Nothing in this post helps me since it takes the current date and not a pre-defined date
– Mark