Reputation: 12625
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.
Upvotes: 3
Views: 4333
Reputation: 2452
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/
Upvotes: 7
Reputation: 66
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.
Upvotes: 4