matus
matus

Reputation: 1582

How to convert local time stored as UTC to actual correct UTC value

I have local time stored in mongodb e.g. "2016-04-25T09:30:00.000Z" It's saved as 'UTC' (Z at the end) but in fact it's literal representation of local time. I have also timezone stored, e.g. "Europe/London" so i have all the info i need to convert to correct utc time.

In that cause result should be "2016-04-25T08:30:00.000Z" but i can't find the way how to do it. I tried moment-timezone.

Upvotes: 0

Views: 168

Answers (3)

Iana Mykhailenko
Iana Mykhailenko

Reputation: 583

I do believe that problem is the format which specifies 000Z zone for moment lib. It says that it's already UTC 0 and timezone = 'Europe/London' is ignored in such case.

moment.utc(moment(start).tz(timezone)).format()

is working correctly with date format"2016-04-25T09:30:00". Check out runnable version here

Upvotes: 2

Maggie Pint
Maggie Pint

Reputation: 2452

There is a much easier and less error prone way than what you have there. Simply parse the date with a format that ignores the Z at the end:

moment.tz("2016-04-25T09:30:00.000Z", 'YYYY-MM-DDTHH:mm:ss:SSS', 'Europe/London').format()
"2016-04-25T09:30:00+01:00"

The date having been parsed correctly, getting the UTC date is as simple as calling .toISOString()

moment.tz("2016-04-25T09:30:00.000Z", 'YYYY-MM-DDTHH:mm:ss:SSS', 'Europe/London').toISOString()
"2016-04-25T08:30:00.000Z"

Note that if that is a local date, regardless of timezone, you can omit the timezone identifier and just use the browser's local time:

moment("2016-04-25T09:30:00.000Z", 'YYYY-MM-DDTHH:mm:ss:SSS').format()
"2016-04-25T09:30:00-05:00"

But I think that you're using Node so that second one probably isn't what you want.

Upvotes: 2

matus
matus

Reputation: 1582

Found it!

var start = "2016-04-25T09:30:00.000Z";
var timezone = 'Europe/London';
var mZoned = moment.tz(start, timezone);
var mStart = moment.utc(start);
var correctedStart = moment.utc(1000*(mStart.unix() - (mZoned.utcOffset()*60)));

Upvotes: 0

Related Questions