简体   繁体   English

如何在访客的本地时区中将UTC字符串转换为momentJS?

[英]How to convert a UTC string into a momentJS in visitor's local timezone?

I have the following Javascript string that represents a moment in time in Coordinated Universal Time (UTC): 我有以下Javascript字符串,它们表示世界协调时间(UTC)中的某个时刻:

myUTCString = "2014-11-06 00:00:00";

I want to use moment.js to convert this string to a moment localized to the timezone of the visitor's browser. 我想使用moment.js将该字符串转换为本地化为访问者浏览器时区的时间。 How can I do it? 我该怎么做?

I tried this: 我尝试了这个:

moment(moment.utc("2014-11-06 00:00:00")).local()

but it yielded me this: 但这给了我:

在此处输入图片说明

As you can see, that object does not contain an attribute _d showing me string value of the localized time. 如您所见,该对象不包含属性_d向我显示本地化时间的字符串值。 But that's not what I need. 但这不是我所需要的。 I need an actual moment object of the local time so that I can further manipulate/use it later in my code. 我需要一个本地时间的实际矩对象,以便稍后可以在代码中进一步操作/使用它。 How can it be done? 如何做呢? It seems like something that would be very commonly needed. 似乎非常需要这些东西。

I have found this fiddle: https://jsfiddle.net/FLhpq/4/ 我发现了这个小提琴: https : //jsfiddle.net/FLhpq/4/

UTC<br/>
<div id="divUTC"></div><br/>
  Your Local Time with respect to above UTC time<br/>
<div id="divLocal">
</div>

$(function(){
     setInterval(function(){
         var divUtc = $('#divUTC');
         var divLocal = $('#divLocal');  
         //put UTC time into divUTC  
         divUtc.text(moment.utc().format('YYYY-MM-DD HH:mm:ss'));      

         //get text from divUTC and conver to local timezone  
         var localTime  = moment.utc(divUtc.text()).toDate();
         localTime = moment(localTime).format('YYYY-MM-DD HH:mm:ss');
         divLocal.text(localTime);        
     },1000);
});

I hope this is exactly what you need - utc time in string is converted to localized time moment. 我希望这正是您所需要的-字符串中的utc时间转换为本地化时间。

There is a much easier way to do this. 有一种更简单的方法可以做到这一点。

If you know you have a utc date, and you wish to convert it to the user's local time, simply do the following: 如果您知道自己有一个UTC日期,并且希望将其转换为用户的本地时间,则只需执行以下操作:

moment.utc("2014-11-06 00:00:00").local()

This yields a moment in the user's local time. 这样就产生了用户本地时间的片刻。 The results of .format() on this moment will be in the user's local time. 此时的.format()结果将以用户的本地时间为准。

Do not look at the value of _d . 不要看_d的值。 It is not accurate. 这是不准确的。 See the following: http://momentjs.com/guides/#/lib-concepts/internal-properties/ 请参阅以下内容: http : //momentjs.com/guides/#/lib-concepts/internal-properties/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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