Easy way to get day number of current quarter?

后端 未结 9 1960
暖寄归人
暖寄归人 2021-01-31 18:39

PHP provides ways to get the number of the current day of the month (date(\'j\')) as well as the number of the current day of the year (date(\'z\')). Is there a way to get the n

相关标签:
9条回答
  • 2021-01-31 19:35
    <?php
    function day_of_quarter($ts=null) {
        if( is_null($ts) ) $ts=time();
        $d=date('d', $ts);
        $m=date('m', $ts)-1;
        while($m%3!=0) {
            $lastmonth=mktime(0, 0, 0, $m, date("d", $ts),   date("Y",$ts));
            $d += date('t', $lastmonth);
            $m--;
        }
        return $d;
    }
    echo day_of_quarter(mktime(0, 0, 0, 1, 1,2009));
    echo "\n";
    echo day_of_quarter(time());
    echo "\n";
    ?>
    
    0 讨论(0)
  • 2021-01-31 19:40

    How about:

    $curMonth = date("m", time());
    $curQuarter = ceil($curMonth/3);
    
    0 讨论(0)
  • 2021-01-31 19:40

    I've noticed that this thread went a bit beyond the question, and it's the first response to many google searches with "Quarter" & "PHP" in them.

    If you're working with the ISO standards of organization, which you should if you're doing a business app, then

    $curMonth = date("m", time());
    $curQuarter = ceil($curMonth/3);
    

    Is NOT correct, because the first day of a year in the ISO standards, can be 30, or 31 December.

    Instead, you should use this :

      $current_yearly_cycle_year_number = 2019;
      $current_yearly_cycle_start->setISODate( $current_yearly_cycle_year_number, 1, 1 );
      $current_yearly_cycle_end->setISODate( $current_yearly_cycle_year_number, 53, 1 );
    
      if( $current_yearly_cycle_end->format("W") !== "53" )
        $current_yearly_cycle_end->setISODate( $current_yearly_cycle_year_number, 52, 1 );
    
      $week_number_start = intval( $current_yearly_cycle_start->format( "W" ) );
      $timestamp_start_quarter = ( $week_number_start === 1 ? 1 : intval( ceil( $current_yearly_cycle_start->format( "m" ) / 3 ) ) );
    
      var_dump( $timestamp_start_quarter );
    
    0 讨论(0)
提交回复
热议问题