简体   繁体   中英

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):

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. 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. 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/

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.

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:

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.

Do not look at the value of _d . It is not accurate. See the following: http://momentjs.com/guides/#/lib-concepts/internal-properties/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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