为了账号安全,请及时绑定邮箱和手机立即绑定

PHP获取每月的星期数

PHP获取每月的星期数

PHP
慕的地6264312 2019-10-11 10:26:31
所以我有一个脚本,可以返回特定月份和年份中的星期数。我该如何从该月开始的某一天,确定是该月的第1,2,3,4或5周的一部分?
查看完整描述

3 回答

?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

太多的“单行”-所需的变量,以避免与条件重新计算。在我参加会议时扔了一个默认参数。


function weekOfMonth($when = null) {

    if ($when === null) $when = time();

    $week = date('W', $when); // note that ISO weeks start on Monday

    $firstWeekOfMonth = date('W', strtotime(date('Y-m-01', $when)));

    return 1 + ($week < $firstWeekOfMonth ? $week : $week - $firstWeekOfMonth);

}

请注意weekOfMonth(strtotime('Oct 31, 2011'));将会返回6; 与OP的预期相反,一些罕见的月份有6周的时间。自从ISO周从星期一开始以来,2017年1月又是6个ISO周的月份-星期日是去年的第一个星期。


对于starshine531,要返回0该月的索引周,请将更改return 1 +为return 0 +或return (int)。


对于Justin Stayton,从星期日开始而不是星期一开始的几周,我将使用strftime('%U'代替date('W',如下所示:


function weekOfMonth($when = null) {

    if ($when === null) $when = time();

    $week = strftime('%U', $when); // weeks start on Sunday

    $firstWeekOfMonth = strftime('%U', strtotime(date('Y-m-01', $when)));

    return 1 + ($week < $firstWeekOfMonth ? $week : $week - $firstWeekOfMonth);

}

对于此版本,2017-04-30现在在四月的第六周,而2017-01-31现在在第五周。


查看完整回答
反对 回复 2019-10-11
?
一只萌萌小番薯

TA贡献1795条经验 获得超7个赞

public function getWeeks($timestamp)

{

    $maxday    = date("t",$timestamp);

    $thismonth = getdate($timestamp);

    $timeStamp = mktime(0,0,0,$thismonth['mon'],1,$thismonth['year']);    //Create time stamp of the first day from the give date.

    $startday  = date('w',$timeStamp);    //get first day of the given month

    $day = $thismonth['mday'];

    $weeks = 0;

    $week_num = 0;


    for ($i=0; $i<($maxday+$startday); $i++) {

        if(($i % 7) == 0){

            $weeks++;

        }

        if($day == ($i - $startday + 1)){

            $week_num = $weeks;

        }

      }     

    return $week_num;

}

您好,我整天都在努力尝试找出此代码,我终于明白了,所以我想我将与大家分享。


您需要做的就是在函数中添加一个时间戳,它会将星期几返回给您。


谢谢


查看完整回答
反对 回复 2019-10-11
  • 3 回答
  • 0 关注
  • 503 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信