简体   繁体   中英

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.

The isoDateToLocalDate seems to be OK, however in the formatTime you need to use UTC methods, otherwise you are getting the host local values, not the adjusted UTC values.

Also, in ISO 8601 terms (and general convention outside computer programming), an offset of 360 represents a timezone of +0600, not -0600. See note below.

 // ISOTimeString = 2017-05-05T00:25:11.378Z // ECMAScript offsetInMinutes = 360; (GMT-0600) function isoDateToLocalDate(ISOTimeString, offsetInMinutes) { var newTime = new Date(ISOTimeString); return new Date(newTime.getTime() - (offsetInMinutes * 60000)); } // localIsoDate: 2017-05-04T18:25:11.378Z Date object function formatTime(localIsoDate) { function z(n){return (n<10?'0':'')+n} var hh = localIsoDate.getUTCHours(); var mm = localIsoDate.getUTCMinutes(); var ss = localIsoDate.getUTCSeconds(); return z(hh)+':'+z(mm)+':'+z(ss); } var timeString = '2017-05-05T00:25:11.378Z'; var offset = 360; console.log(formatTime(isoDateToLocalDate(timeString, offset))) 

ECMAScript timezone signs are the reverse of the usual convention. If the client timezone offset is +0600 then their host will show -360.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM