Convert date yyyy-mm-ddThh:mm:ss. z to dd/mm/yyyy with javascript

Asked

Viewed 1,140 times

1

How to convert the date of yyyy-mm-ddThh:mm:ss.z for dd/mm/aaaa?

Example: 2018-07-19T22:07:00.000-03:00 for 19/07/2018

I searched everywhere (including stackoverflow in English and Portuguese) a solution for this with javascript, only found with other languages.

  • Take a look here: https://answall.com/questions/6526/comorformatar-data-no-javascript

  • Nothing in this post helps me since it takes the current date and not a pre-defined date

1 answer

2


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.