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

3

2

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?
Superfetation answered 28/5, 2021 at 7:45 Comment(3)
Replace Z with 000Z? It's just milliseconds vs. nanoseconds or something.Underhill
@ChrisG oh ok, I thought it was some special value.Superfetation
@IamL.i have posted an answer .Gardell
H
0

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.

Hyperbaric answered 28/5, 2021 at 7:53 Comment(0)
G
0

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

Gardell answered 28/5, 2021 at 8:34 Comment(0)
D
0

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.

Durkin answered 28/5, 2021 at 15:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.