Home > Net >  Laravel - Carbon: how compare two dates (string) without timezone?
Laravel - Carbon: how compare two dates (string) without timezone?

Time:11-30

i'm having a trouble on comparing two dates in laravel. In my app i have a date field to compare:

// example
$order_date = Carbon::now()->format('Y-m-d') // returns "2022-11-30"
$now = Carbon::now() // returns an object with date at the bottom date: 2022-11-30 15:51:58.207817 Europe/Rome ( 01:00)

I need to check this condition:

 if ($order_date->lessThan($now)) {
     return redirect()->back()->with('error', 'Message error');
   }

The problem is that i have to compare only the date, not also the time. So i'm getting this error:

Call to a member function lessThan() on string

For avoid this error i made some changes like this:

$date = Carbon::parse($order_date)->addHour(00)->addMinute(00)->addSeconds(00);
$now = Carbon::today()

By this way both objects return this date:

^ Carbon\Carbon @1669762800 {#1317 ▼
  #endOfTime: false
  #startOfTime: false
  #constructedObjectId: "00000000000005250000000000000000"
  #localMonthsOverflow: null
  #localYearsOverflow: null
  #localStrictModeEnabled: null
  #localHumanDiffOptions: null
  #localToStringFormat: null
  #localSerializer: null
  #localMacros: null
  #localGenericMacros: null
  #localFormatFunction: null
  #localTranslator: null
  #dumpProperties: array:3 [▶]
  #dumpLocale: null
  #dumpDateProperties: null
  date: 2022-11-30 00:00:00.0 Europe/Rome ( 01:00)
}

^ Carbon\Carbon @1669762800 {#1243 ▼
  #endOfTime: false
  #startOfTime: false
  #constructedObjectId: "00000000000004db0000000000000000"
  #localMonthsOverflow: null
  #localYearsOverflow: null
  #localStrictModeEnabled: null
  #localHumanDiffOptions: null
  #localToStringFormat: null
  #localSerializer: null
  #localMacros: null
  #localGenericMacros: null
  #localFormatFunction: null
  #localTranslator: null
  #dumpProperties: array:3 [▶]
  #dumpLocale: null
  #dumpDateProperties: null
  date: 2022-11-30 00:00:00.0 Europe/Rome ( 01:00)
}

As you can see by this way i can use the lessThan() method and it seems to be fine.

But is there any other simplier way to do this? To compare two date strings like "2022-11-30" and "2022-11-29" ?

CodePudding user response:

For your case you can use createFromFormat:

$dateOne = Carbon::createFromFormat('Y-m-d', '2022-11-30');
$dateTwo = Carbon::createFromFormat('Y-m-d', '2022-11-29');

$result = $dateOne->lessThan($dateTwo); //returns false

CodePudding user response:

Strings can be compared in pure PHP

if ("2022-12-05" > "2022-11-29") {
    echo "yes";
}
  • Related