Search code examples
phpphp-carbondayjs

dayJS date function to PHP Carbon


I have the following date processing in dayjs which I am trying to replicate in PHP but failing. I expect both to return Monday 27 July 2020. Can someone help?

JS - returns Monday 27 July 2020

var firstOfMonth = dayjs('2020-08-01'),
    weekOneStart = firstOfMonth.clone().day(1); // Monday

console.log(weekOneStart);

PHP - returns Monday 3 August 2020

$d = Carbon::createFromFormat('Y-m-d', '2020-08-01');
echo $d->firstOfMonth(1);

Solution

  • The two functions are different, as the JS function gets the first Monday of the week, while the Carbon function gets the first Monday of the month. You can see this in the Carbon code for firstOfMonth:

    public function firstOfMonth($dayOfWeek = null)
    {
        $this->startOfDay();
    
        if ($dayOfWeek === null) {
            return $this->day(1);
        }
    
        return $this->modify('first '.static::$days[$dayOfWeek].' of '.$this->format('F').' '.$this->year);
    }
    

    If you want to get the first day of the week, then you need to use $d->startOfWeek();

    $d = Carbon::createFromFormat('Y-m-d', '2020-08-01');
    $d->startOfWeek();
    // object(Carbon\Carbon)(
    //   'date' => '2020-07-27 00:00:00.000000',
    //   'timezone_type' => 3,
    //   'timezone' => 'America/New_York'
    // )