knnhcn
knnhcn

Reputation: 1151

Moment.js resolve timezone offset

I'm working in an Angular 6 front end and receive from another system time stamps which have no time zones (C# backend, DateTime). I suspect that javascript is automatically adding the local time zone to Date objects.

Example:

Receiving from backend: 2018-10-15T07:53:00.000Z

When console logging: console.log(timestamp) // Mon Oct 15 2018 09:53:00 GMT+0200

I am using moment.js and already tried moment.utc() and moment(DATE).utc(). But it still adds the local time zone especially because I have to re-transform my moment objects back to the type Date with .toDate().

How can I resolve the time zone difference and get back a utc date to work with or the same structure as received?

Upvotes: 0

Views: 2964

Answers (2)

bbsimonbb
bbsimonbb

Reputation: 28982

Your input is UTC and will be parsed just fine. Javascript Dates have no notion of timezone! The local timezone is applied by the static methods for serializing (Date.toString(), Date.toDateString() etc.) (Console.log(Date) uses Date.toString().)

Use Date.toLocaleString([],{timeZone:"UTC"}). Forcing UTC, you will see in the output the same time as the input. Much more details are here :-)

Here it is working:

console.log(new Date('2018-10-15T07:53:00.000Z').toLocaleString([],{timeZone:'UTC'}))

Upvotes: 1

manish kumar
manish kumar

Reputation: 4692

try to format use as per desired.

let str = '2018-10-15T07:53:00.000Z';
let moment = moment(str).utcOffset(str)
console.log(moment.format('DD/MM/YYYY HH:mm'))
<script src="https://momentjs.com/downloads/moment.js"></script>

Second Snippet (to use the date object from string)

let str = '2018-10-15T07:53:00.000Z';
let moment = moment(str).utcOffset(str);
console.log(moment.toDate())
<script src="https://momentjs.com/downloads/moment.js"></script>

Upvotes: 1

Related Questions