Monday 8 May 2017

Format Localized Iso date to hh:mm:ss

I am trying to convert a UTC date to local time on my node server and finally return the localized time in the format of hh:mm:ss (not using Moment JS). I'm passing in the timezone offset from the client to Node, which is GMT-6.

My original time is: 2017-05-05T00:25:11.378Z

// ISOTimeString = `2017-05-05T00:25:11.378Z`
// offsetInMinutes = 360; (GMT - 6)
function isoDateToLocalDate(ISOTimeString, offsetInMinutes) {
  var newTime = new Date(ISOTimeString);
  return new Date(newTime.getTime() - (offsetInMinutes * 60000));
}

The localized time is 2017-05-04T18:25:11.378Z, which is correct (2017-05-05T00:25:11 - 6 hours = 2017-05-04T18:25:11).

// localIsoDate: 2017-05-04T18:25:11.378Z Date object
function formatTime(localIsoDate) {
  var hh = localIsoDate.getHours();
  var mm = localIsoDate.getMinutes();
  var ss = localIsoDate.getSeconds();
  return [hh, mm, ss].join(':');
}

// formatted: 12:25:11

The problem is, while still on the server, when I try to format into hh:mm:ss, it subtracts another 6 hours, giving me 12:25:11. I don't want to convert again, I simply want to format and display 18:25:11 from the already localized time.

How can I do this?


Note: Keep in mind I do not have the option to convert timezones after it's passed back to the client in my case.



via Growler

No comments:

Post a Comment