beginner
beginner

Reputation: 73

How to change the timezone with moment.js without changing the time?

I have a datepicker which returns local time in the format dddd, MMMM DO YYYY, h:mm:ss a to a variable localTime. I have an option to change the timezone from a <select> which contains timezone names from moment.tz.names(). When timezone changes, I need to change the timezone of localTime to new timezone without changing the time.How can I do this with moment.js

let timeString = "Wednesday, January 10th 2018, 9:10:19 pm";
let localTime = moment(timeString, 'dddd, MMMM DO YYYY, h:mm:ss a').format('YYYY-MM-DD HH:mm:ss ZZ');
let localTimeInUtc = moment(timeString, 'dddd, MMMM DO YYYY, h:mm:ss a').utc().format('YYYY-MM-DD HH:mm:ss ZZ');
let newTimezone = "EST";
let newTime = moment(timeString, 'dddd, MMMM DO YYYY, h:mm:ss a').tz(newTimezone).format('YYYY-MM-DD HH:mm:ss ZZ');
let newTimeInUtc = moment(timeString, 'dddd, MMMM DO YYYY, h:mm:ss a').tz(newTimezone).utc().format('YYYY-MM-DD HH:mm:ss ZZ');
console.log(localTime);
console.log(localTimeInUtc);
console.log(newTime);
console.log(newTimeInUtc);

Here time in UTC is same for localTime and newTime

Upvotes: 4

Views: 5408

Answers (1)

Vignesh Raja
Vignesh Raja

Reputation: 8781

According to Docs

Maybe you are looking for format2 in the following code.

format1 - creates moment and sets the time-zone (will not update the offset). format2 - creates the moment with the given timezone.

var date = moment().format("dddd, MMMM D YYYY, h:mm:ss a"), format = "dddd, MMMM D YYYY, h:mm:ss a", timezone = "America/New_York";
var format1 = moment(date,format).tz(timezone);
var format2 = moment.tz(date, format,timezone);
console.log(format1.format(format)+" -> "+format1.format());
console.log(format2.format(format)+" -> "+format2.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data.min.js"></script>

See this Github issue once.

Upvotes: 2

Related Questions