How to convert time from UTC to say “Pacific/Easter”?

问题: I am getting time from server as "19:30" but it needs to be converted to "Pacific/Easter time zone. I have tried things like let t = "19:30:00"; let utc = moment.utc(t...

问题:

I am getting time from server as "19:30" but it needs to be converted to "Pacific/Easter time zone.

I have tried things like

 let t = "19:30:00";
let utc = moment.utc(t);
let z = moment(utc).utcOffset(-300).format('HH:mm');

But I am going wrong somewhere.

I have seen in my dev app version that it is being converted to 14:30 which is like -5:00 hours.

So, how do I get similar result for this?

Here's something else that I tried

let t = "19:30:00"; 
let tt = moment.tz(t, "UTC");
let nt = tt.clone().tz("Pacific/Easter"); 

and I am getting nt as "19:30:00" also. so , it's not converting at all

this is the one that seems to be working. but it's not showing the correct result

let t = "19:30:00";
let utc = moment.utc(t, 'HH:mm:ss');
let z = utc.tz('Pacific/Easter').format('HH:mm');
console.log(z);

it should show the result as 19:30 -5 hours which should be 14:30, but it shows the result as 13:30. so, anyone knows why this is happening??


回答1:

You need moment-timezone to get this working.

var newYork    = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");

回答2:

You have to use tz() function from moment-timezone.

First you have to parse your input specifying format ('HH:mm:ss') to moment.utc since it is not in ISO 8601 format, then convent it to given timezone using tz().

Here a live sample:

let t = "19:30:00";
let utc = moment.utc(t, 'HH:mm:ss');
let z = utc.tz('Pacific/Easter').format('HH:mm');
console.log(z);
<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.17/moment-timezone-with-data-2012-2022.min.js"></script>

  • 发表于 2018-07-10 16:37
  • 阅读 ( 246 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除