php strtotime “last monday” if today is monday?

后端 未结 8 1762
攒了一身酷
攒了一身酷 2020-11-30 03:45

I want to use strtotime(\"last Monday\").

The thing is, if today IS MONDAY, what does it return? It seems to be returning the date for the monday of la

8条回答
  •  我在风中等你
    2020-11-30 04:19

    As it was correctly outlined in the previous answer, this trick works, but also had caveats prior to PHP 5.6.22, PHP 7.0.7 and PHP 7.1-dev:

    strtotime('last monday', strtotime('tomorrow'));
    
    // or this one, which is shorter, but was buggy:
    strtotime('Monday this week');
    

    To those, who prefer the "Jedy-way", to work with objects of the DateTime class, the solution is next:

    (new \DateTime())->modify('tomorrow')->modify('previous monday')->format('Y-m-d');
    

    or even shorter notation:

    \DateTime('Monday this week')
    

    Be carefull, because if you do the same on SQL, you don't need to have any of these tricks in mysql with addition of "tomorrow". Here's how the solution will look:

    SELECT DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY) as last_monday;
    

提交回复
热议问题