问题
I'm using date-fns
to return some values as shown below:
import { format, formatDistance } from "date-fns";
var date = new Date("2019-03-06 00:00:00");
console.log(format(new Date(date), "dd MMM, y"));
It works fine on Chrome and returns We Mar, y
But returns Invalid Date
in Safari.
I believe it's because the date ("2019-03-06 00:00:00") is not in ISO 8601 format. But this is the format I'm receiving from an endpoint. Is there any option to convert this to the right format and make it work on Safari?
回答1:
I see two issues:
You're relying on a nonstandard input format the first time you parse the date.
You're passing a
Date
into theDate
constructor, which forces it to convert the date to a string, then parse the string.
I'd only parse it once, and use the standard date/time format when calling new Date
the first time:
import { format, formatDistance } from "date-fns";
var date = new Date("2019-03-06T00:00:00");
// Note -----------------------^
console.log(format(date, "dd MMM, y"));
// No `new Date` ^
Note that your string will be parsed as local time (on spec-compliant JavaScript engines¹) because it includes the time portion of the string. Unfortunately this varied after the format was added in ES2015, updated in ES2016, but where it's ended up is:
When the UTC offset representation is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.
Since your string doesn't have a UTC offset (no Z
or +00:00
or similar), and does have a time, it's parsed in local time. (Again, on spec-compliant JavaScript engines¹).
My recommendation is either don't parse date strings with the built-in Date
object, or make sure you always have a timezone indicator on the string if you do.
¹ RobG pointed out that Safari parses new Date("2019-03-06T00:00:00")
as UTC. Sadly, this is a bug in JavaScriptCore, Apple's JavaScript engine. It affects not only Safari, but Chrome on iOS as well (and probably any other iOS browser; I've tested Brave, Opera, and Dolphin), since Chrome has to use JavaScriptCore instead of its usual V8 on iOS because apps can't allocate executable memory, so JIT engines can't be used on iOS. But the V8 team have made an interpreter-only version of V8, so maybe Chrome (and Brave) on iOS will be updated to use that if it's fast enough.
来源:https://stackoverflow.com/questions/55655273/date-fns-returns-invalid-date-on-safari