[英]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.