'Javascript date showing a different time by using New Date
I have a following date time
'2021-08-05T12:38:27.163z'
when I am trying to use it
new Date('2021-08-05T12:38:27.163z')
it returns
Thu Aug 05 2021 18:08:27 GMT+0530 (India Standard Time)
Date wise it is fine as it is in the given string, but about time it is not returning the correct time
can any one help me with this ?
Solution 1:[1]
'2021-08-05T12:38:27.163z' is the UTC time format, where it is used regardless of any timezone.
But when you are displaying datetime, mostly you will need to display your local time, in this case is your India Standard Time (GMT+0530)
e.g. if you want to get hours, which you still can get both your local and the UTC hours:
const d = new Date('2021-08-05T12:38:27.163z')
d.getHours()
d.getUTCHours()
Solution 2:[2]
Convert the local time back to UTC.
var d = new Date('2021-08-05T12:38:27.163z');
var n = d.toUTCString();
console.log(n)
Solution 3:[3]
You can also display the UTC time with toISOString().
const d = new Date('2021-08-05T12:38:27.163z')
const isoTime = d.toISOString()
//2021-08-05T12:38:27.163Z
For another input:
const d = new Date('2021-08-05 12:00 UTC')
const isoTime = d.toISOString()
//2021-08-05T12:00:00.000Z
If the string for new Date does not contain a UTC identifier, then the time is interpreted as local time. The UTC time is then usually different.
const d = new Date('2021-08-05 12:00')
const isoTime = d.toISOString()
//2021-08-05T10:00:00.000Z
(Local time zone Europe/berlin daylight saving time)
Solution 4:[4]
z is the zone designator for the zero UTC offset
so new Date('2021-08-05T12:38:27.163z') will be displayed in your local timezone .
so if you want the same time appeating remove the z
new Date('2021-08-05T12:38:27.163')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Xin |
| Solution 2 | Ritik Banger |
| Solution 3 | |
| Solution 4 | Charfeddine Mohamed Ali |
