使用DateTime类获取本周首尾日期
// 获取本周的第一天和最后一天
具体代码如下所示:
$date = new DateTime();
$date->modify('this week');
$first_day_of_week = $date->format('Y-m-d');
$date->modify('this week +6 days');
$end_day_of_week = $date->format('Y-m-d');经过测试发现 modify 方法的实际用途可能不如预期明确,因此这里提供另外两个替代示例。
参考代码如下:
// 获取本星期的星期一
// @timestamp 参数表示某个星期的特定时间戳,默认为当前时间
// @is_return_timestamp 参数决定返回值类型,若为 true 则返回时间戳,否则返回时间格式字符串
function this_monday($timestamp=0, $is_return_timestamp=true) {
static $cache;
$id = $timestamp . $is_return_timestamp;
if (!isset($cache[$id])) {
if (!$timestamp) $timestamp = time();
$monday_date = date('Y-m-d', $timestamp - 86400 * date('w', $timestamp) + (date('w', $timestamp) > 0 ? 86400 : /*6*86400*/ 518400));
if ($is_return_timestamp) {
$cache[$id] = strtotime($monday_date);
} else {
$cache[$id] = $monday_date;
}
}
return $cache[$id];
}
// 获取本星期的星期天具体代码如下:
// @timestamp 参数表示某个星期的特定时间戳,默认为当前时间
// @is_return_timestamp 参数决定返回值类型,若为 true 则返回时间戳,否则返回时间格式字符串
function this_sunday($timestamp=0, $is_return_timestamp=true) {
static $cache;
$id = $timestamp . $is_return_timestamp;
if (!isset($cache[$id])) {
if (!$timestamp) $timestamp = time();
$sunday = this_monday($timestamp) + /*6*86400*/ 518400;
if ($is_return_timestamp) {
$cache[$id] = $sunday;
} else {
$cache[$id] = date('Y-m-d', $sunday);
}
}
return $cache[$id];
}