简体   繁体   中英

How to check if date of year has passed using Carbon/Laravel?

In Laravel, I'm trying to check if the current date is before or after a specific date in any year . A client's fiscal year ends October 31st and I'm having trouble checking if today is before or after that.

I've tried using the built in comparison functions in Carbon but I can't figure out what to compare now() with, since all Carbon instances seems to include a specific year. How do I check if now() has passed that day in any calender year?

The code below works but using dayOfYear() will return different values on leap years and seems like a poor solution.

if (now()->dayOfYear >= 304) {
    $current_year = now()->year;
} else {
    $current_year = now()->year - 1;
}

How can I return true if now() is after October 31st in any year?

It looks like you already know about using getters with the Carbon object to find pieces of the date. If you're looking to see if the current date is after October 31, just use them some more:

if (now()->month > 10) {
    $current_year = now()->year;
} else {
    $current_year = now()->subYear()->year;
}

To check if the current date is before any given date


$isBefore31October = now()->lt(Carbon::parse('2020-10-31'));

//Will return false if now() occurs after 31st October 2020

Similarly to check if the current date occurs after a given date

$isAfter31October = now()->gt(Carbon::parse('2020-10-31'));

//Will return true if now() occurs after 31st October 2020

For setting the current year depending upon whether current date occurs after 31st October of current year

$fyEnd = Carbon::parse(now()->year . "-10-31");

$current_year = now()->gt($fyEnd) ? now()->year : now()->year - 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM