Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two Carbon Timestamps?

I have two timestamps, edited_at which I created and created_at (Laravel's)... In database, both have type timestamp and default value 0000-00-00 00:00:00... But

var_dump(edited_at variable) is giving string. While var_dump(created_at variable) is object/Carbon. What is wrong with these timestamps?

I have to compare both after converting into integer using format('U'). I can only call this method on Carbon Object. How can I do that?

like image 262
Hassan Saqib Avatar asked Apr 16 '15 19:04

Hassan Saqib


People also ask

Can we compare two dates?

In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.

How can I compare two dates in PHP?

Once you have created your DateTime objects, you can also call the diff() method on one object and pass it the other date in order to calculate the difference between the dates. This will give you back a DateInterval object. $last = new DateTime( "25 Dec 2020" ); $now = new DateTime( "now" );


1 Answers

First, Eloquent automatically converts it's timestamps (created_at, updated_at) into carbon objects. You could just use updated_at to get that nice feature, or specify edited_at in your model in the $dates property:

protected $dates = ['edited_at']; 

Now back to your actual question. Carbon has a bunch of comparison functions:

  • eq() equals
  • ne() not equals
  • gt() greater than
  • gte() greater than or equals
  • lt() less than
  • lte() less than or equals

Usage:

if($model->edited_at->gt($model->created_at)){     // edited at is newer than created at } 
like image 200
lukasgeiter Avatar answered Oct 06 '22 00:10

lukasgeiter