简体   繁体   中英

Converting moment UTC to Local date time

I put a UTC .NET/JSON date from .net on client side. When I run the following command:

moment(value.Planet.when).utc()

The returned date from webservice:

"/Date(1469271646000)/"

I get a date in the _d parameter showing the current accurate UTC date with GMT+0300 on right side.

I want to convert this time to local time on the user machine and what ever I do, I always get the time 3 hours back.

I do this:

moment(value.Planet.when).local().format('YYYY-MM-DD HH:mm:ss')

and I get the same date time as the UTC. I don't understand how can I get momentjs to show the UTC time relative to the local time. I checked that the momentjs object is indeed UTC.

I thought that if I pass the moment.utc() function the UTC date that I've got from the webservice (originally from the database), I can just run the local() function and I'll get the accurate hour relative to my area, but it didn't work.

You can use moment(date).format('YYYY-MM-DDTHH:mm:ss');

Eg:- if you date "/Date(1469271646000)/"

ip-> moment(1469271646000).format('YYYY-MM-DDTHH:mm:ss');

op-> "2016-07-23T16:30:46"

Do not use the _d property. It is for internal use only. See this answer , the user guide , or Maggie's blog post on the subject .

As far as you question of how to convert to local time, you don't actually need to convert at all. You're already parsing the input value in local mode, so you can just use it directly:

var m = moment("/Date(1469271646000)/");  // gives you a moment object in local mode.
var s = m.format();   // lets you format it as a string.  Pass parameters if you like.
var d = m.toDate();   // gives you a Date object if you really need one

Try to avoid using Date objects unless they're required by some other controls or libraries you're using. Most operations can be done strictly on moment objects.

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