首页 文章

通过php找到一周的第一天[复制]

提问于
浏览
13

可能重复:获取PHP中的第一天?

嗨,

我想查找本周和上周的第一个和最后一个日期 . 同样,我想查找当月和上个月的第一个和最后一个日期 .

这必须在PHP中完成 . 请帮忙 .

2 回答

  • 43

    strtotimerelative time formats非常强大:

    strtotime('monday this week');
    strtotime('sunday this week');
    strtotime('monday last week');
    strtotime('sunday last week');
    

    (这仅适用于PHP 5.3)

    strtotime('first day of this month');
    strtotime('last day of this month');
    strtotime('first day of last month');
    strtotime('last day of last month');
    

    为了获得PHP <5.3中一个月的第一个和最后一个日期,您可以使用mktimedate的组合( date('t') 给出该月的天数):

    mktime(0,0,0,null, 1); // gives first day of current month
    mktime(0,0,0,null, date('t')); // gives last day of current month
    
    $lastMonth = strtotime('last month');
    mktime(0,0,0,date('n', $lastMonth), 1); // gives first day of last month
    mktime(0,0,0,date('n', $lastMonth), date('t', $lastMonth); // gives last day of last month
    

    如果你只想获得一个字符串进行演示,那么你不需要 mktime

    date('Y-m-1'); // first day current month
    date('Y-m-t'); // last day current month
    date('Y-m-1', strtotime('last month')); // first day last month
    date('Y-m-t', strtotime('last month')); // last day last month
    
  • 3

    这是一周的第一天和最后一天的功能:

    function week_start_date($wk_num, $yr, $first = 1, $format = 'F d, Y') 
    { 
        $wk_ts  = strtotime('+' . $wk_num . ' weeks', strtotime($yr . '0101')); 
        $mon_ts = strtotime('-' . date('w', $wk_ts) + $first . ' days', $wk_ts); 
        return date($format, $mon_ts); 
    } 
    
    $sStartDate = week_start_date($week_number, $year); 
    $sEndDate   = date('F d, Y', strtotime('+6 days', strtotime($sStartDate)));
    

    它也许可以适应月份,但我想得到我的答案! :)

相关问题