Date conversion

Asked

Viewed 96 times

6

I have a date in this format

"2017-10-13T18:15:41.143Z"

And I would like a date in this format

10/06/2017 01:42:34 PM (-0300)

How can I make the conversion?

  • Maybe Timezone @vnbrs

  • (-0300) would be the time difference compared to the GMT time.

1 answer

4


I created a formatting function, basically dismembered the date and was concatenating gradually.

I concateno zero the left in a few moments to ensure that it gets 2 digits.

In the hours I make a calculation and check whether it is greater or equal to 12 to indicate whether it is PM or AM.

I use the function getTimezoneOffset() that returns the difference in minutes from the time zone.

function formatDate(date) {
  var dia       = ("00" + date.getDate()).slice(-2);
  var mes       = date.getMonth()+1;
  var ano       = date.getFullYear();
  var minutos   = ("00" + date.getMinutes()).slice(-2);
  var segundos  = ("00" + date.getSeconds()).slice(-2);
  var timezone  = date.getTimezoneOffset();
  var horas     = date.getHours() % 12 ? date.getHours() % 12 : 12;
  
  horas = ("00" + horas).slice(-2);
  var txtHoras = horas >= 12 ? 'PM' : 'AM';
  
  var retorno;
  retorno = dia + '/' + mes + '/' + ano + ' ';
  retorno = retorno + horas + ':' + minutos + ':' + segundos;
  retorno = retorno + ' ' + txtHoras + ' (' + timezone + ')';
  return  retorno;
}

console.log(new Date()); 
console.log(formatDate(new Date())); 

Browser other questions tagged

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