1

I'm using node.js to select info from my mysql database and I have a datetime column, but I'm not getting the format I want.

This is my sql code SELECT id, data, titulo, subtitulo, texto, DATE(datahora_cadastro) as data FROM sig_noticias

I need the data to be like this: DD/MM/YYYY But I'm getting this: Thu Mar 30 2017 00:00:00 GMT-0300 (GMT-03:00)

1 Answer 1

1

Easiest way to format dates in Javascript is by far using a modern date / time library. I personally use MomentJS and it works well. I highly recommend this solution if you plan on working with dates in even just a few areas of your app.

Using moment, you could simply call moment(myDate).format("DD/MM/YYYY");.

If you really want to stick to pure Javascript, however, here's how to get the format you want:

const formattedDate = `${myDate.getDate() + 1}/${myDate.getMonth() + 1}/${myDate.getFullYear()}`;

Javascript's built-in date functions are pretty confusing. Here, for instance, the getDate and getMonth methods return the index of the date / month, and not the actual date / month, so we need to add +1 to those.

Using vanilla Javascript then becomes even harder when dealing with date manipulation (adding, subtracting) and timezones.

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

3 Comments

I'm sorry @FláviaNunes there was a typo in my format string. I fixed it now.
Thank you!! I'll use moment forever now haha
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… with suitable locale should do the trick e.g. (new Date()).toLocaleDateString("en-GB").

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.