![](/img/trans.png)
[英]How to compare dates when DST is changing with Laravel / Carbon
[英]Laravel - Carbon: how compare two dates (string) without timezone?
我在比較 laravel 中的兩個日期時遇到了麻煩。在我的應用程序中,我有一個要比較的日期字段:
// 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)
我需要檢查這個條件:
if ($order_date->lessThan($now)) {
return redirect()->back()->with('error', 'Message error');
}
問題是我必須只比較日期,而不是時間。 所以我收到這個錯誤:
在字符串上調用成員 function lessThan()
為了避免這個錯誤,我做了一些這樣的改變:
$date = Carbon::parse($order_date)->addHour(00)->addMinute(00)->addSeconds(00);
$now = Carbon::today()
通過這種方式,兩個對象都返回這個日期:
^ 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)
}
正如您通過這種方式看到的,我可以使用 lessThan() 方法,它似乎沒問題。
但是還有其他更簡單的方法嗎? 要比較兩個日期字符串,如“2022-11-30”和“2022-11-29”?
對於您的情況,您可以使用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
字符串可以比較純 PHP
if ("2022-12-05" > "2022-11-29") {
echo "yes";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.