Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

momentjs toDate() - timezone gets reset

I am working with momentjs and converting dates to different time zones using convertedDate = moment().utcOffset(timezone).format(). This works well but it is a string and I need to transform it to date object.

I've tried new Date(convertedDate) and moment().utcOffset(timezone).toDate() but that returns my current timezone as a date object. How can I keep the converted timezone?

like image 586
cocoa Avatar asked Mar 18 '15 20:03

cocoa


People also ask

How do I change timezone in Momentjs?

To change the default time zone, use moment. tz. setDefault with a valid time zone.

How do I get local timezone in Momentjs?

var tz = moment. tz. guess(); It will return an IANA time zone identifier, such as America/Los_Angeles for the US Pacific time zone.

How do I get the current time in Momentjs?

To get the current date and time, just call javascript moment() with no parameters like so: var now = moment();

How do I get timezone offset?

Definition and Usage. getTimezoneOffset() returns the difference between UTC time and local time. getTimezoneOffset() returns the difference in minutes. For example, if your time zone is GMT+2, -120 will be returned.


2 Answers

So I wasn't very far off. The format needs to exclude timezone for it to work. This code finally worked how I needed it to.

convertedDate = new Date(moment().utcOffset('-4').format('YYYY-MM-DD HH:mm'));

like image 169
cocoa Avatar answered Nov 13 '22 13:11

cocoa


A cleaner approach to get a native Date object with time according to the timezone, using moment would be following:

convertedDate = moment.utc(moment.tz(timezone).format('YYYY-MM-DDTHH:mm:ss')).toDate()

PS: assuming two things

  • you have imported both 'moment' and 'moment-timezone'.
  • value of timezone is given like 'Asia/Kolkata' instead of an offset value
like image 26
Ameen Ahsan Avatar answered Nov 13 '22 15:11

Ameen Ahsan