Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why new Date().toISOString() is loosing timezone?

I do not want to use any external libs like momentjs, I want to create a formatted date string myself. I tried to use new Date().toISOString() but it's losing time-zone.

This:

new Date()

Gives:

Sat Jun 24 2017 09:32:10 GMT+0300 (RTZ 2 (winter))

And:

new Date().toISOString();

Gives:

2017-06-24T06:32:22.990Z

And 09:32:10 is the right time, so 06:32:22 hass lost timezone information.

To add to this, it looks like new Date().toLocaleString() does almost what I need. At last hours is correct. Result: "24.06.2017, 11:37:05".

like image 500
Dmitry Bubnenkov Avatar asked Jun 24 '17 06:06

Dmitry Bubnenkov


1 Answers

Answer from a similar question

moment.js is great but sometimes you don't want to pull a lage number of dependencies for a simple things.

the following works as well:

var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0,-1); // => '2015-01-26T06:40:36.181'

The slice(0,-1) gets rid of the trailing Z which represents Zulu timezone and can be replaced by your own.

like image 76
Shahar Kazaz Avatar answered Sep 18 '22 01:09

Shahar Kazaz