Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Gabotronix's avatar

Laravel: error comparing javascript Date with Carbon timestamp

in my laravel app I'm trying to check if new records were created after a certain timestam (lastTimeFocused) the thing is I'm getting wrong results...

$newLikes = Like::where('liked_id','=',$request['user_id'])->where('created_at','>',$lastTimeFocused)->get();

Where lastTimeFocused is the last time the app screen was focused, here I'm gettign lots of results that were presumably created "after" but if I check these records the created_at timestamp shows it's not the case...

"lastTimeFocused": 2023-08-03T12:10:33.195Z,
created_at": "2023-08-03T11:56:32.000000Z

How is created_at supposed to be after lastTimeFocused? Maybe I have to format before compare?

I get lastTimeFocused with a simple javascript new Date() on the frontend

0 likes
3 replies
Snapey's avatar

You don't show how you create the record.

Don't see what this has to do with javascript. Thats just added noise in the question.

Presumably both are datetime or timestamp fields in the database?

How is created_at supposed to be after lastTimeFocused?

Don't understand what you are asking.

jumbaeric's avatar

you can convert the new Date() to UTC using the toISOString() method

const lastTimeFocused = new Date();
const lastTimeFocusedUTC = lastTimeFocused.toISOString();

Now, you can send lastTimeFocusedUTC to your Laravel backend. In your Laravel controller, you can convert the UTC timestamp to a Carbon instance in UTC timezone

use Carbon\Carbon;

$lastTimeFocusedUTC = '2023-08-03T12:10:33.195Z';
$lastTimeFocused = Carbon::createFromFormat('Y-m-d\TH:i:s.u\Z', $lastTimeFocusedUTC, 'UTC');

Then you can use this $lastTimeFocused Carbon instance in your query to compare with created_at

$newLikes = Like::where('liked_id', '=', $request['user_id'])
                ->where('created_at', '>', $lastTimeFocused)
                ->get();
Snapey's avatar

@jumbaeric from the question

"lastTimeFocused": 2023-08-03T12:10:33.195Z,

pretty much looks like a ISO UTC timestamp to me

Please or to participate in this conversation.