Skip to content Skip to sidebar Skip to footer

Safari New Date With String Value Outs Different Time

What I am trying to do is changing 'yyyy-mm-dd HH:mm:ss' string to date value. Here is the current code var c = new Date('2019-01-19 23:59:59'.replace(/\s+/g, 'T')) It returns c

Solution 1:

Safari... It does not consider time zone offset when creates an instance with date string.

Add Z to the end is also good point, but if you want to get the same result with other browsers, should calculate timezone offset.

Here is what I have done ...

// Before do this, check navigator.userAgent 
// and execute below logic if it is desktop Safari.

// Add Z is the convention, but you won't get any error even if do not add.
var c = new Date('2019-01-19 23:59:59Z'.replace(/\s+/g, 'T')) 

// It will returns in minute
var timeOffset = new Date().getTimezoneOffset();

// Do not forget getTime, if not, you will get Invalid date         
var d = new Date(c.getTime() + (timeOffset*60*1000))    

Will open this post till tomorrow for waiting better answer. Thanks.


Solution 2:

Add the 'Z' to the date string for GMT/UTC timezone

var c = new Date('2019-01-19 23:59:59'.replace(/\s+/g, 'T')+'Z');

ISO dates can be written with added hours, minutes, and seconds (YYYY-MM-DDTHH:MM:SSZ): Date and time is separated with a capital T.

UTC time is defined with a capital letter Z.

If you want to modify the time relative to UTC, remove the Z and add +HH:MM or -HH:MM instead:

for example var d = new Date("2019-01-19T23:59:59-09:00");


Post a Comment for "Safari New Date With String Value Outs Different Time"