问题
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
- chrome :
Sat Jan 19 2019 23:59:59 GMT+0900 (KST)
- safari :
Sun Jan 20 2019 08:59:59 GMT+0900 (KST)
- ie11 :
Sat Jan 19 2019 23:59:59 GMT+0900 (KST)
What should I do to make it returns all same date?
Thanks.
回答1:
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");
回答2:
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.
来源:https://stackoverflow.com/questions/54210749/safari-new-date-with-string-value-outs-different-time