Formatting date and time with Javascript?

Asked

Viewed 4,321 times

2

I’m consuming data from a API and would like to know how do I pass the following date and time value, to the Brazilian standard.

The format returned is this:

2017-01-05T14:35:17.437

but I’d like it to be shown

05-01-2017
  • 2

    In this specific format, you’ll have to take the result, transform a javascript Date object, take the values you want (day, month and year) and form a new one string. If you want an easier way, just take this value, turn it into a javascript Date object and later use the method toLocaleString(), which will return in this format: dd/mm/yyyy hh:mm:ss

2 answers

2


You can use the momentjs who does all the work of date formatting, calculations, etc.:

moment.locale('pt-br');
console.log(moment('2017-01-05T14:35:17.437').format('DD-MM-YYYY'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>

but it can also be done with the pure :

var data = '2017-01-05T14:35:17.437';
var parte = data.substring(0,10).split('-').reverse().join('-');
console.log(parte);

References:

2

Just see how to string your date and test it:

Ex:

var formatoCompleto = "2017-01-05T14:35:17.437";
var dataFormatada = formatoCompleto.substring(0,formatoCompleto.indexOf("T"));
var dadosData = dataFormatada.split("-");

var dataFinal = dadosData[2]+"-"+dadosData[1]+"-"+dadosData[0];
console.log(dataFinal);

Browser other questions tagged

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