admin管理员组文章数量:1291027
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 monly needed.
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 monly needed.
2 Answers
Reset to default 7There 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./guides/#/lib-concepts/internal-properties/
I have found this fiddle: https://jsfiddle/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.
本文标签: javascriptHow to convert a UTC string into a momentJS in visitor39s local timezoneStack Overflow
版权声明:本文标题:javascript - How to convert a UTC string into a momentJS in visitor's local timezone? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741501297a2382067.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论