Liron Harel
Liron Harel

Reputation: 11247

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.

Upvotes: 0

Views: 1662

Answers (2)

Jinay Shah
Jinay Shah

Reputation: 11

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"

Upvotes: 1

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241900

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.

Upvotes: 0

Related Questions