根据日期获取该日期所在的年、周

需求:

根据日期获取该日期所在的年、周

需求细节:

1.每年的第一个星期日所在的周当作该年的第一周

2.周的定义:周日~次周六

实现方法(PHP):

<?php
/**
 * 根据日期获取该日期所在的年、周
 */
function getWeekByDate($date) {
    $currentYear = date('Y', strtotime($date));

    $firstSunday = '';
    for ($i=0; $i < 7; $i++) { 
        if (date('w', strtotime("+{$i} days", strtotime("{$currentYear}-01-01"))) == 0) {   //该年第一个周日
            $firstSunday = date('Y-m-d', strtotime("+{$i} days", strtotime("{$currentYear}-01-01")));
            break;
        }
    }

    list($currentSunday, $currentSaturday) = getWeekDateRangeByDate($date);

    $year = '';
    $week = '';
    if ($currentSunday < $firstSunday) {    //周数归到上一年,递归再调一次该该方法
        list($year, $week) = getWeekByDate($currentSunday);
    } else {
        $year = $currentYear;
        $dayDiff = day_diff($firstSunday, $currentSunday);
        $week = ($dayDiff / 7) + 1;
    }
    
    return array($year, $week);
}

/**
 * 根据指定日期获取所在周的日期范围
 */
function getWeekDateRangeByDate($date) {
    if (!$date) {
        $date = date('Y-m-d');
    }
    $currentDay = date('w', strtotime($date));
    $firstDateTime = strtotime("$date - $currentDay days");  //周日作为一周的第一天
    $firstDate = date('Y-m-d', $firstDateTime);
    $lastDateTime = $firstDateTime + 6 * 86400;
    $lastDate = date('Y-m-d', $lastDateTime);

    return array($firstDate, $lastDate);
}
?>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值