Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincent15000's avatar

Problem to create a date with Carbon

Hello,

I have a problem with the first date which is never the $monday date. For the second date, I have no problem.

$year = $request->year;
$week = $request->week;

$monday = $this->getMondayFromWeekNumber($year, $week);

$fromDate = CarbonImmutable::createFromFormat('Y-m-d H:i:s', $monday.' 00:00:01');
$toDate = CarbonImmutable::createFromFormat('Y-m-d H:i:s', $monday.' 23:59:59')->addDays(6);

I'm looking around for 2 days without any solution.

Do you have any idea ?

Thanks a lot ;).

Vincent

0 likes
6 replies
Sinnbeck's avatar

Can you show getMondayFromWeekNumber() method, and show the result of dd($monday);

Nakov's avatar

and this method is magical getMondayFromWeekNumber or you can show the content of it?

You can use startOfWeek btw

now()->startOfWeek()->day will give you the correct day.

vincent15000's avatar

@Nakov Hello ... yes it's a magic method ;).

Here is its code.

private function getMondayFromWeekNumber($year, $week, $format = 'Y-m-d')
{
    $firstDayInYear = date('N', mktime(0, 0, 0, 1, 1, $year));
    if ($firstDayInYear < 5) {
        $shift = - ($firstDayInYear - 1) * 86400;
    }
    else {
        $shift = (8 - $firstDayInYear) * 86400;
    }
    if ($week > 1) {
        $weekInSeconds = ($week - 1) * 604800;
    } else {
        $weekInSeconds = 0;
    }
    $timestamp = mktime(0, 0, 0, 1, 1, $year) + $weekInSeconds + $shift;
    return date($format, $timestamp);
}
vincent15000's avatar

I just found the solution : it wasn't a Carbon problem, it was another problem, I forgot to change a fixed test code somewhere.

Snapey's avatar
Snapey
Best Answer
Level 122

by the way, this is the same as your 'magic' method;

function getMondayFromWeekNumber($year, $week, $format = 'Y-m-d')
{
    return (new Carbon())->setISODate($year, $week)->format($format); 
}
vincent15000's avatar

Wow thank you @snapey I did'nt even know that this method exists. Effectively it will be much easier.

Please or to participate in this conversation.