15 July 2017

I've been using the wrong date delimiters in PHP for JavaScript

So I've been making dates in PHP like this

$dt = new DateTime("2017-07-15");
$date = $dt->format("Y-m-d");

and passing that to JS like this

echo "foo = new Date(\"$date\");";
// returns: Sat Jul 15 2017 00:00:00 GMT+0300 (FLE Summer Time)

and that was working fine in Chrome and Firefox. However, if you try and call foo in Safari, you'll get an invalid date error. This is because Safari doesn't currently support the dash delimiter format. More info.

To avoid this in the future, I need to start remembering to format my dates in php with / instead of - when I'm going to be using it in the web-page. So like this

$dt = new DateTime("2017/07/15");
$date = $dt->format("Y/m/d");

The only thing I can see still needing dashes, would be in URLs. If you need to switch to dashes while in JS, you can do something like .replace(/\//g, "-")

I've been neglecting testing in Safari which is pretty bad. Luckily, you can still download an old version of Safari for Windows, so testing is easy enough.

No comments:

Post a Comment