Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
50
rated 0 times [  54] [ 4]  / answers: 1 / hits: 15105  / 9 Years ago, wed, march 18, 2015, 12:00:00

Using moment.js, I'm attempting to extract the offset from an ISO date string so I can use the offset later when formatting an epoch timestamp to ensure the conversion of the timestamp is in the same timezone.



Even though the offset in the string is -0400, the result is always 0;



var currentTime = 2015-03-18T16:10:00.001-0400;
var utcOffset = moment(currentTime).utcOffset(); // 0


I've attempted to use parseZone() as well without success. Is there a way to extract -0400 from the string so I can use it while formatting another time?



Thanks for the help!
KC


More From » momentjs

 Answers
365

The correct way to extract the offset is indeed with parseZone



var currentTime = 2015-03-18T16:10:00.001-0400;
var utcOffset = moment.parseZone(currentTime).utcOffset();


This should result in -240, which means 240 minutes behind UTC, which is the same as the -0400 in the input string. If you wanted the string form, instead of utcOffset() you could use .format('Z') for -04:00 or .format('ZZ') for -0400.



The form you gave in the question just uses the computer's local time zone. So it is currently UTC+00:00 in your time zone (or wherever the code is running), that would explain why you would get a zero. You have to use parseZone to retain the offset of the input string.



Also - your use case is a bit worrying. Remember, an offset is not the same thing as a time zone. A time zone can change its offset at different points in time. Many time zones do this to accommodate daylight saving time. If you pick an offset off of one timestamp and apply it to another, you don't have any guarantees that the offset is correct for the new timestamp.



As an example, consider the US Eastern time zone, which just changed from UTC-05:00 to UTC-04:00 when daylight saving time took effect on March 8th, 2015. If you took a value like the one you provided, and applied it to a date of March 1st, you would be placing it into the Atlantic time zone instead of the Eastern time zone.


[#67390] Monday, March 16, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
wilson

Total Points: 27
Total Questions: 93
Total Answers: 93

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
wilson questions
Tue, Aug 9, 22, 00:00, 2 Years ago
Wed, May 11, 22, 00:00, 2 Years ago
Wed, May 20, 20, 00:00, 4 Years ago
Wed, May 13, 20, 00:00, 4 Years ago
;