Moment: When building a UTC date with Moment.js, zone() setter does nothing (2.8.3)

Created on 11 Sep 2014  ·  3Comments  ·  Source: moment/moment

I get the exact same moment object after running zone(-1) as I do when I don't run it. Example:

console.log( moment().utc().toDate() );
console.log( moment().utc().zone(-1).toDate() );

I would expect this to adjust the Date object according to the timezone offset, but it does... well, nothing.

Most helpful comment

@rquinlivan I dug a little deeper. You can pass a second argument to zone() to make it keep the wall-clock time the same:

> moment().format()
'2014-09-15T16:59:30-04:00'
> moment().zone(-1).format()
'2014-09-15T21:59:35+01:00'
> moment().zone(-1, true).format()
'2014-09-15T16:59:38+01:00'

So you'll end up with:

> moment().toDate()
Mon Sep 15 2014 17:00:16 GMT-0400 (EDT)
> moment().zone(-1, true).toDate()
Mon Sep 15 2014 12:00:19 GMT-0400 (EDT)

Which I believe is what you want.

FWIW, everyone will be quicker to help you with open source if you approach a functionality gap with "hey, I need this feature, how can I help?" rather than as you did.

All 3 comments

Moment keeps track of instances in time (i.e. milliseconds since 1970 UTC). What you're doing when you say utc() or zone(), you're changing how that time is _expressed_ (i.e. we say "9:00" in EST but "6:00" in PST, but it's the same time). So converting it back in to a date drops the "you should print dates differently" metadata. It's still the same time.

It sounds like you want to modify the actual time? We don't have a "mutate the time so that it will be displayed the same way in this other zone" feature, though, we've discussed it (or do we, @ichernev?)

Yes, I want to modify the actual time. This is pretty limiting and I will likely have to stop using this library because of this limitation.

@rquinlivan I dug a little deeper. You can pass a second argument to zone() to make it keep the wall-clock time the same:

> moment().format()
'2014-09-15T16:59:30-04:00'
> moment().zone(-1).format()
'2014-09-15T21:59:35+01:00'
> moment().zone(-1, true).format()
'2014-09-15T16:59:38+01:00'

So you'll end up with:

> moment().toDate()
Mon Sep 15 2014 17:00:16 GMT-0400 (EDT)
> moment().zone(-1, true).toDate()
Mon Sep 15 2014 12:00:19 GMT-0400 (EDT)

Which I believe is what you want.

FWIW, everyone will be quicker to help you with open source if you approach a functionality gap with "hey, I need this feature, how can I help?" rather than as you did.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

BCup picture BCup  ·  3Comments

alvarotrigo picture alvarotrigo  ·  3Comments

dbshwang picture dbshwang  ·  3Comments

Shoroh picture Shoroh  ·  3Comments

danieljsinclair picture danieljsinclair  ·  3Comments