Why is (Laravel's (Carbon) toISOString different from Javascript's toISOString? How to make them the same?

Viewed 564

So In JS if you do:

new Date().toISOString()

it will give you:

"2021-05-28T07:39:31.401Z"

But in PHP/Carbon (Laravel):

// I passed the same date from js result above
 (new \Carbon\Carbon("2021-05-28T07:39:31.401Z"))->toISOString();

will return:

"2021-05-28T07:39:31.401000Z"
  • What's the additional three 0 on laravel/php's date?
  • Any way I can make JS to return the same format?
3 Answers

I do not know why they are different. I'll do some research on it.

You'll be better off by making PHP return the Javascript format, as formatting dates in JS can get quite verbose.

Personally, I always have a constant that I call DATE_ISO_JS with this value Y-m-d\TH:i:s.u\Z. That does the trick for me.

You can format using Carbon package

\Carbon\Carbon::createFromFormat('Y-m-d\TH:i:s.u\Z',"2021-05-28T07:39:31.401Z"))->format('Y-m-d\TH:i:s.v\Z'))

This result will be

"2021-05-28T07:39:31.401Z"

s - Seconds, with leading zeros (00 to 59)

u - Microseconds

that's simple, they both follow ISO 8601 but this norm does not precise the decimal precision. Also note that the ISO 8601 norm allows both comma or dot (, or .) as the decimal separator, but recommend the comma! That's obviously not very conveniant for English-based programmation languages, so they both use . but all the above are valid ISO 8601 strings:

2021-05-28T07:39:31.40Z
2021-05-28T07:39:31+03:00
2021-05-28T07:39:31,4017+0300
2021-05-28T07:39:31.401099999999+0300

Basically new Date() in JS has millisecond-precision and new DateTime() in PHP has microsecond-precision, so they just gives youthe maximum precision they have but note that both can easily read strings with any decimal length.

Related