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?
To change the default time zone, use moment. tz. setDefault with a valid time zone.
var tz = moment. tz. guess(); It will return an IANA time zone identifier, such as America/Los_Angeles for the US Pacific time zone.
To get the current date and time, just call javascript moment() with no parameters like so: var now = moment();
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.
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'));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With