Ben
Ben

Reputation: 3357

moment tz convert string

This should be simple, but I spent hours going over documentation and still got nothing. I have this string:

var time = "2018-09-29 23:50:21"

This time is in UTC, even though it does not say so, I know it is.

I want to convert it to PST (America/Los_Angeles) with .tz

I tried:

moment(time).tz('America/Los_Angeles').format(MomentDefaults.DateTime);

I get "Sep 29, 2018, 23:50"

I tried MANY different combination that failed in different ways.

I want to be able to print "Sep 29, 2018, 16:50" which is time in utc converted to pst.

What am I missing?

Upvotes: 0

Views: 1516

Answers (1)

Akrion
Akrion

Reputation: 18515

Can you change your time string to be an actual valid ISO UTC string since you are sure it is?

var time = "2018-09-29T23:50:21.000Z"

console.log(moment(time).tz('America/Los_Angeles').format())  //16:50
console.log(moment(time).tz('America/New_York').format())     //19:50
<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.21/moment-timezone-with-data.min.js"></script>

Make sure you have the data for the timezones loaded etc as per the docs:

In Node.js, all the data is preloaded. No additional code is needed for loading data.

When using Moment Timezone in the browser, you will need to load the data as well as the library.

Upvotes: 1

Related Questions