Get the date of next monday, tuesday, etc

前端 未结 10 1167
轻奢々
轻奢々 2020-11-29 02:24

I would like to find the date stamp of monday, tuesday, wednesday, etc. If that day hasn\'t come this week yet, I would like the date to be this week, else, next week. Thank

10条回答
  •  Happy的楠姐
    2020-11-29 03:04

    I know it's a bit of a late answer but I would like to add my answer for future references.

    // Create a new DateTime object
    $date = new DateTime();
    
    // Modify the date it contains
    $date->modify('next monday');
    
    // Output
    echo $date->format('Y-m-d');
    

    The nice thing is that you can also do this with dates other than today:

    // Create a new DateTime object
    $date = new DateTime('2006-05-20');
    
    // Modify the date it contains
    $date->modify('next monday');
    
    // Output
    echo $date->format('Y-m-d');
    

    To make the range:

    $monday = new DateTime('monday');
    
    // clone start date
    $endDate = clone $monday;
    
    // Add 7 days to start date
    $endDate->modify('+7 days');
    
    // Increase with an interval of one day
    $dateInterval = new DateInterval('P1D');
    
    $dateRange = new DatePeriod($monday, $dateInterval, $endDate);
    
    foreach ($dateRange as $day) {
        echo $day->format('Y-m-d')."
    "; }

    References

    PHP Manual - DateTime

    PHP Manual - DateInterval

    PHP Manual - DatePeriod

    PHP Manual - clone

提交回复
热议问题