PHP DateTime() class, change first day of the week

2020-01-27 06:40发布

The DateTime class in PHP (5.3+) works just great as long as the first day of the week in your country is Sunday. In the Netherlands the first day of the week is Monday and that just makes the class useless for building a calendar with week view and calculations.

I can't seem to find an answer on Stackoverflow or the rest of the Internet on how to have DateTime act as if the first day of the week is Monday.

I found this piece on Stackoverflow, but it doesn't fix all the ways you can get into trouble and it's not an elegant solution.

$dateTime = new DateTime('2012-05-14');
$monday = clone $dateTime->modify(('Sunday' == $dateTime->format('l')) ? 'Monday last week' : 'Monday this week');

Is there a way to change this or extent DateTime? Can't imagine it's not a setting as most of Europe starts their weeks on monday.

Added: Posting the full calendar and functions code will not make things clearer. But here is one one line for example. I often have to check what the first day of the week is or calculate from the first day of the week to a different date and time in that week. My code is getting full of these:

$startOfWeek = $date->modify(('Sunday' == $date->format('l')) ? 'Monday last week' : 'Monday this week')->modify('+3 hours')->format(DATETIME);

I also get an unwanted result trying to get the first full week of the month or year. As my $date object doesn't always contain the same date I have to keep checking it this way, making the code difficult to read. Having a lot more programming to do on this calendar I can't forsee where it's going to bug again.

EDIT There are some inconsistencies though. For some strange reason DateTime does get this next one right:

$test = new DateTime('2012-10-29'); // Monday
echo $test->modify('Sunday this week')->format('Y-m-d');  // 2012-11-04

// But...

$test = new DateTime('2012-11-04'); // Sunday
echo $test->modify('Monday this week')->format('Y-m-d');  // 2012-11-05 instead of 2012-10-29   

But I think I can make the question clearer: Can the DateTime() class be used with monday as the first day of the week. If not, can the class be extended to use monday as the first day of the week.

UPDATE: Ok, I think I'm getting somewhere... I'm not a pro at coding classes..but this seems to work for the weeks. But it still needs rules for first day, second day... and also for the day name Sunday itself. I don't think this is foolproof. I would appreciate any help to fix it.

class EuroDateTime extends DateTime {

// Fields
private $weekModifiers = array (
    'this week',
    'next week',
    'previous week',
    'last week'
);

// Override "modify()"
public function modify($string) {

    // Search pattern
    $pattern = '/'.implode('|', $this->weekModifiers).'/';

    // Change the modifier string if needed
    if ( $this->format('N') == 7 ) { // It's Sunday
        $matches = array();
        if ( preg_match( $pattern, $string, $matches )) {
            $string = str_replace($matches[0], '-7 days '.$matches[0], $string);
        }
    }
    return parent::modify($string);

}

}
// This works
$test = new EuroDateTime('2012-11-04');
echo $test->modify('Monday this week')->format('Y-m-d');
// And I can still concatenate calls like the DateTime class was intended
echo $test->modify('Monday this week')->modify('+3 days')->format('Y-m-d');

4条回答
Ridiculous、
2楼-- · 2020-01-27 07:06

You can also get the start and the end of the week with setISODate, the last parameter is the ISO-daynumber in the week, monday is 1 and sunday 7

$firstday = new \DateTime();
$lastday = clone($firstday);
$firstday->setISODate($firstday->format("Y"),$firstday->format("W"),1);
$lastday->setISODate($firstday->format("Y"),$firstday->format("W"),7);
查看更多
Viruses.
3楼-- · 2020-01-27 07:07

There's nothing to stop you manually modifying a date to get the "first" day of the week, depending on your definition of "first". For instance:

$firstDayOfWeek = 1; // Monday
$dateTime = new DateTime('2012-05-16'); // Wednesday

// calculate how many days to remove to get back to the "first" day
$difference = ($firstDayOfWeek - $dateTime->format('N'));
if ($difference > 0) { $difference -= 7; }
$dateTime->modify("$difference days");

var_dump($dateTime->format('r')); // "Mon, 14 May 2012 00:00:00 +0000"

Notice how the output changes as you vary $firstDayOfWeek; if it was changed to 4 above (Thursday), it would then consider Thu, 10 May 2012 as the "first" day.

Edit: this is a rather basic example. The correct way to do this is by using the user/system's locale to give you the "first" day, and compute from there. See this question for more information.

查看更多
叼着烟拽天下
4楼-- · 2020-01-27 07:14

I too am confused about what the problem is, because DateTime does have a notion of the week starting from Monday: The N format gives you the days of the week counting from Monday to Sunday, with Monday being 1 and Sunday being 7. Moreover, the W format, the only way to get a week number, also starts the week on Monday. (I seem to remember that Dutch week numbers aren't exactly like ISO week numbers, but that's a different story). So what feature are you missing exactly?

Edit So the problem is (only?) that the relative datetime formats, such as "Monday this week" give the wrong result when the reference date is a Sunday. From the docs it sounds like DateTime just defers to strtotime, which is supposed to be locale-dependent. So if you have your locale set properly and this is not working, it sounds like a bug (for what that's worth).

查看更多
女痞
5楼-- · 2020-01-27 07:15

I found this to work, yet there are some inconsistencies in PHP's DateTime class.

If the departing date is a sunday the previous monday is not considered the same week (fixed by this class). But departing from a monday, the next sunday is considered as the same week. If they fix that in the future this class will need some additions.

class EuroDateTime extends DateTime {

// Override "modify()"
public function modify($string) {

    // Change the modifier string if needed
    if ( $this->format('N') == 7 ) { // It's Sunday and we're calculating a day using relative weeks
        $matches = array();
        $pattern = '/this week|next week|previous week|last week/i';
        if ( preg_match( $pattern, $string, $matches )) {
            $string = str_replace($matches[0], '-7 days '.$matches[0], $string);
        }
    }
    return parent::modify($string);

}

}
查看更多
登录 后发表回答