简体   繁体   中英

Change moment date string into proper timezone

I have a date with time and a timezone.

I need this formatted a specific way, which is why I am using moment.

Say the date string I want to put in is 2018-12-31 02:00:00.000 +00:00

I convert it into a specific format doing the following:

const properDate = moment(date, 'YYYY-MM-DD hh:mm:ss:ms')

However this is assuming the date is in UTC, and I want it to be in America/New York timezone, so the date and time I am expecting is actually:

2018-12-30 21:00:00.000

So my question is, how do I add in the timezone to moment when converting a date/time to a specific format? I know it isn't as simple as passing a parameter. Is it another function I should call?

I have tried

const properDate = moment(date, 'YYYY-MM-DD hh:mm:ss:ms').tz('America/New_York')

but that didn't work either.

Edit: I should also mention that I am also using moment-timezone . It just seems that I can't get it to format the way I need it to as well as get it in the proper timezone.

So basically, I would think I could do something like:

const momentDate = moment(date)
const properDate = momentDate.tz(timezone).format('YYYY-MM-DD hh:mm:ss:ms')

Unfortunately as long as I try to format it, it won't work either.

Use moment.tz for parsing time string using a given timezone (eg 'America/New_York' ) while tz() is for converting between zones.

Here a live sample:

 const date = '2018-12-30 21:00:00.000'; const properDate = moment.tz(date, 'YYYY-MM-DD hh:mm:ss.SSS', 'America/New_York') console.log(properDate.format()); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM