Search code examples
phpdatephp-carbon

PHP Carbon specialized date format


I want to make a function that will output a result like this:

//Assuming that today is 2022-01-20
parse_date("2022-01-20") //Today
parse_date("2022-01-19") //Yesterday
parse_date("2022-01-18") //Tuesday
parse_date("2022-01-17") //Monday
parse_date("2022-01-16") //Sunday
parse_date("2022-01-15") //2022-01-15

The idea is to display Today if the date is today, Yesterday if the date is yesterday, the weekday name if the date is within the current week and Y-m-d for anything else. The current code I have that works is as follows:

public function parse_date($date) {
    $carbonDate = Carbon::parse($date);
    if($carbonDate->isToday()) return "Today";
    if($carbonDate->isYesterday()) return "Yesterday";
    $now = Carbon::now();
    $start = $now->startOfWeek(CarbonInterface::SUNDAY)->copy();
    if($carbonDate >= $start && $carbonDate <= $now->endOfWeek(CarbonInterface::SATURDAY)->copy()) {
        return $carbonDate->format('l');
    }
    
    return $carbonDate->format('Y-m-d');
}

What I want to know is if there's a better way to do this using other Carbon functions.


Solution

  • Another way to do it is to check the week, and compare it to the current week. Double-check the values first to make sure this works, or if you need to change the locale, with Carbon::parse($date)->locale('en_US');

    public function parse_date($date) {
        $carbonDate = Carbon::parse($date);
        if($carbonDate->isToday()) return "Today";
        if($carbonDate->isYesterday()) return "Yesterday";
        if($carbonDate->week == Carbon::now()->week) {
            return $carbonDate->format('l');
        }
        
        return $carbonDate->format('Y-m-d');
    }