Flávia Nunes
Flávia Nunes

Reputation: 271

How can I format the date from mysql (I'm using node.js)?

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)

Upvotes: 1

Views: 1332

Answers (1)

Samuel Bolduc
Samuel Bolduc

Reputation: 19173

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.

Upvotes: 1

Related Questions