Home >Backend Development >PHP Tutorial >Explain the relevant content of php to obtain the specified date
Due to work needs, I need to get the start and end dates of the week starting from Thursday, and PHP does not provide a method to get the start and end dates of this week, so I wrote a method for future use.
Calculation method:
<?php/** * 计算指定日期的一周开始及结束日期 * @param DateTime $date 日期 * @param Int $start 周几作为一周的开始 1-6为周一~周六,0为周日,默认0 * @retrun Array */function getWeekRange($date, $start=0){ // 将日期转时间戳 $dt = new DateTime($date); $timestamp = $dt->format('U'); // 获取日期是周几 $day = (new DateTime('@'.$timestamp))->format('w'); // 计算开始日期 if($day>=$start){ $startdate_timestamp = mktime(0,0,0,date('m',$timestamp),date('d',$timestamp)-($day-$start),date('Y',$timestamp)); }elseif($day<$start){ $startdate_timestamp = mktime(0,0,0,date('m',$timestamp),date('d',$timestamp)-7+$start-$day,date('Y',$timestamp)); } // 结束日期=开始日期+6 $enddate_timestamp = mktime(0,0,0,date('m',$startdate_timestamp),date('d',$startdate_timestamp)+6,date('Y',$startdate_timestamp)); $startdate = (new DateTime('@'.$startdate_timestamp))->format('Y-m-d'); $enddate = (new DateTime('@'.$enddate_timestamp))->format('Y-m-d'); return array($startdate, $enddate); }?>
Example: The test starts from Monday to Sunday to calculate the start and end time of the week
<?php$date = '2016-04-27';for($start=0; $start<=6; $start++){ list($startdate, $enddate) = getWeekRange($date, $start); echo 'date:'.$date.' week start:'.$start.' range:'.$startdate.', '.$enddate.'<br>'; }?>
Output:
date:2016-04-27 week start:0 range:2016-04-24, 2016-04-30date:2016-04-27 week start:1 range:2016-04-25, 2016-05-01date:2016-04-27 week start:2 range:2016-04-26, 2016-05-02date:2016-04-27 week start:3 range:2016-04-27, 2016-05-03date:2016-04-27 week start:4 range:2016-04-21, 2016-04-27date:2016-04-27 week start:5 range:2016-04-22, 2016-04-28date:2016-04-27 week start:6 range:2016-04-23, 2016-04-29
This article explains the relevant content of php to obtain the specified date. For more related knowledge, please pay attention to the php Chinese website.
Related recommendations:
Detailed explanation of how PHP generates a unique RequestID class
How to check the database table capacity through MySQL
Explanation on how to use php str_getcsv to parse a string into an array
The above is the detailed content of Explain the relevant content of php to obtain the specified date. For more information, please follow other related articles on the PHP Chinese website!