Tonic
Tonic

Reputation: 45

Why am I getting the proceeding week when using datetime modify

I am trying to get an array of days starting from Monday and ending on Saturday, and then be able to get the next set of days but skipping Sunday and so on and so forth

Here is my current code.

function getWeek($w){
    $d = [];
    $week = $w ?? 0;
    $dw = new \DateTime();
    $dw->modify(''.$week.' week monday');
    for($i = 0; $i < 6; $i++){
        $d[$i] = $dw->format('Y-m-d');
        if($i == 5){
            $dw->modify('+2 day');
        }else{
            $dw->modify('+1 day');
        }
    }
    return $d;
}

This roughly gets what I want but when the default value is 0, it sometimes skips the current week and shows next week.

Here is what I get, http://sandbox.onlinephpfunctions.com/code/667a34fb5180104250288fd372213d24b43b0ef3

If I put -1 as the week offset it gets the current week but on the following Monday it will still get this week and not the current week.

Is it something to do with the default timezone(UTC)? or can I fix this by using a different function

Upvotes: 0

Views: 42

Answers (1)

Sami Akkawi
Sami Akkawi

Reputation: 342

The main issue is the Monday in your first modify, this finds the next Monday.

Try this solution:

function getWeek($w){
    $d = [];
    $week = $w ?? 0;
    $currentDateTime = new \DateTime();
    $mondayDateTime = (new \DateTime())->modify('Monday');
    
    if ($currentDateTime->format('Y-m-d') !== $mondayDateTime->format('Y-m-d')) {
        $mondayDateTime->modify('-1 week');
    }

    $mondayDateTime->modify($w . ' Weeks');
    
    for($i = 0; $i < 6; $i++){
        $d[$i] = $mondayDateTime->format('Y-m-d');
        if($i == 5){
            $mondayDateTime->modify('+2 day');
        }else{
            $mondayDateTime->modify('+1 day');
        }
    }
    return $d;
}

Upvotes: 2

Related Questions