How to find the date of a day of the week from a date using PHP?

后端 未结 9 1714
说谎
说谎 2020-11-27 03:59

If I\'ve got a $date YYYY-mm-dd and want to get a specific $day (specified by 0 (sunday) to 6 (saturday)) of the week that YYYY-

相关标签:
9条回答
  • 2020-11-27 04:31

    Just:

    2012-10-11 as $date and 5 as $day

    <?php
    $day=5;
    $w      = date("w", strtotime("2011-01-11")) + 1; // you must add 1 to for Sunday
    
    echo $w;
    
    $sunday = date("Y-m-d", strtotime("2011-01-11")-strtotime("+$w day"));
    
    $result = date("Y-m-d", strtotime($sunday)+strtotime("+$day day"));
    
    echo $result;
    
    ?>
    

    The $result = '2012-10-12' is what you want.

    0 讨论(0)
  • 2020-11-27 04:33

    Try

    $date = '2012-10-11';
    $day  = 1;
    $days = array('Sunday', 'Monday', 'Tuesday', 'Wednesday','Thursday','Friday', 'Saturday');
    echo date('Y-m-d', strtotime($days[$day], strtotime($date)));
    
    0 讨论(0)
  • 2020-11-27 04:35

    PHP Manual said :

    w Numeric representation of the day of the week

    You can therefore construct a date with mktime, and use in it date("w", $yourTime);

    0 讨论(0)
  • 2020-11-27 04:37

    I had to use a similar solution for Portuguese (Brazil):

    <?php
    $scheduled_day = '2018-07-28';
    $days = ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb'];
    $day = date('w',strtotime($scheduled_day));
    $scheduled_day = date('d-m-Y', strtotime($scheduled_day))." ($days[$day])";
    // provides 28-07-2018 (Sáb)
    
    0 讨论(0)
  • 2020-11-27 04:39

    If your date is already a DateTime or DateTimeImmutable you can use the format method.

    $day_of_week = intval($date_time->format('w'));
    

    The format string is identical to the one used by the date function.


    To answer the intended question:

    $date_time->modify($target_day_of_week - $day_of_week . ' days');
    
    0 讨论(0)
  • 2020-11-27 04:41

    I think this is what you want.

    $dayofweek = date('w', strtotime($date));
    $result    = date('Y-m-d', strtotime(($day - $dayofweek).' day', strtotime($date)));
    
    0 讨论(0)
提交回复
热议问题