AlexK
AlexK

Reputation: 396

Moment.js format giving wrong UTC Offset

I am in PST and my current UTC offset should be -07:00.

When I do this I correctly get the offset:

const offset = new Date().getTimezoneOffset();
const o = Math.abs(offset);
return (offset < 0 ? '+' : '-') + ('00' + Math.floor(o / 60)).slice(-2) + ':' + ('00' + (o % 60)).slice(-2);

However when I use Moment.js like this:

const date = new Date().getTimezoneOffset();
return moment(date).format('Z'); 

I get -08:00.

What's the deal?

Upvotes: 0

Views: 802

Answers (1)

jhpratt
jhpratt

Reputation: 7130

In your second example, what you're doing is setting the creating a moment object from the offset. If you inspect the date object created, you should see that it's moment("1969-12-31T16:00:00.420").

What you should be doing is creating a moment object from the date, not the offset. Doing this will yield the correct result.

const date = new Date();
return moment(date).format('Z'); // "-07:00" for PDT

Upvotes: 2

Related Questions