Brian Var
Brian Var

Reputation: 6227

How to convert UTC + Offset Date to Local?

I have stored a value in an SQLServer DB in UTC which is 2016-07-28 16:00:00.000:

enter image description here

I've converted that UTC DateTime string to an ISO string in Javascript then passed that value into a moment and called toDate() on it.

But the value output is still UTC including the offset.

So I stepped through the results of the two assignments and found the following values at each stage:

1st assignment: (UTC value 4:15 pm form DB converted to ISOString)

var isoDate = new Date('7/28/2016 4:15:00 PM').toISOString(); 

output value: "2016-07-28T15:15:00.000Z"

2nd assignment: (Being output as UTC plus offset instead of expected 17:15 local)

var localOutageStart = moment.utc(isoDate).toDate();

output value:  Thu Jul 28 2016 16:15:00 GMT+0100 (GMT Daylight Time)

Instead I'd like to output the value in local by using the offset, so it would output this value instead in local:

desired output value:  28 07 2016 17:15:00

How can I instead output the local moment time instead of UTC plus offset? I pass the result to a Bootstrap datetime picker which I think takes a moment value.

Upvotes: 3

Views: 841

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241890

If 2016-07-28 16:00:00.000 is in UTC, then you need to treat it as such. As ISO8601, it should be 2016-07-28T16:00:00.000Z. You can get this with moment like so:

var i = "2016-07-28 16:00:00.000";
var s = moment.utc(i).toISOString();

Or without moment, like so:

var i = "2016-07-28 16:00:00.000";
var s = new Date(i + " UTC").toISOString();  // yes, a non-standard hack, but works.

This creates the string: "2016-07-28T16:00:00.000Z"

Then when you want to use it on the client side:

var i = "2016-07-28T16:00:00.000Z";
var m = moment(i);  // here's a moment object you can use with your picker
var d = m.toDate(); // or, if you want a Date object

// or, if you want to custom format a string
var s = m.format("DD MM YYYY HH:mm:ss");

Or if you want to do this with the Date object alone:

var i = "2016-07-28T16:00:00.000Z";
var d = new Date(i);

(But custom formating is more difficult without moment)

Upvotes: 2

Related Questions