0

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?

knnhcn
  • 1,071
  • 1
  • 11
  • 22

2 Answers2

1

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>
manish kumar
  • 4,412
  • 4
  • 34
  • 51
  • Thank you for the answer. The problem is, `.format()` returns a string which is correctly formatted indeed, but I need a Date object for further work (e.g. date comparison). – knnhcn Oct 18 '18 at 06:54
  • 1
    @knnhcn there is a moment().toDate(); – manish kumar Oct 18 '18 at 06:57
  • Indeed, but in the docs it reads: `As Javascript Date: To get a copy of the native Date object that Moment.js wraps`. So it's basically only a wrapper and you get the same result as native js `.toDate()`. [link](https://momentjs.com/docs/#/displaying/as-javascript-date/) – knnhcn Oct 18 '18 at 07:06
1

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'}))
bbsimonbb
  • 27,056
  • 15
  • 80
  • 110