How to compare two Carbon Timestamps?

心已入冬 提交于 2019-11-27 06:29:30

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
}

Carbon has a bunch of comparison functions with mnemonic names:

  • equalTo()
  • notEqualTo()
  • greaterThan()
  • greaterThanOrEqualTo()
  • lessThan()
  • lessThanOrEqualTo()

Usage:

 if($model->edited_at->greaterThan($model->created_at)){
     // edited at is newer than created at
 }

Valid for nesbot/carbon 1.36.2

if you are not sure what Carbon version you are on, run this

$composer show "nesbot/carbon"
ginna

First, convert the timestamp using the built-in eloquent functionality, as described in this answer.

Then you can just use Carbon's min() or max() function for comparison. For example:

$dt1 = Carbon::create(2012, 1, 1, 0, 0, 0); $dt2 = Carbon::create(2014, 1, 30, 0, 0, 0); echo $dt1->min($dt2);

This will echo the lesser of the two dates, which in this case is $dt1.

See http://carbon.nesbot.com/docs/

extending on @lukasgeiter answer, the methods eq(), ne(), gt(), gte(), lt(), lte() not just compare the day but it also look at the time and timezone

>> $date->toArray();

{
  "year": 2019,
  "month": 2,
  "day": 23,
  "dayOfWeek": 6,
  "dayOfYear": 53,
  "hour": 7,
  "minute": 39,
  "second": 52,
  "micro": 849616,
  "timestamp": 1550907592,
  "formatted": "2019-02-23 07:39:52",
  "timezone": {
    "timezone_type": 3,
    "timezone": "UTC"
  }
}

Time zone can be adjusted as Carbon::parse($stringDate, new DateTimeZone('Asia/Dubai'))

to compare only the day

$date1->startOfDay()->eq($date2->startOfDay())

i couldn't use these methods, hope it helps someone else.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!