获得当前季度的简单方法?

Cha*_*son 21 php date date-arithmetic

PHP提供了获取当月(日期('j'))的数量以及当年的当天数(日期('z'))的方法.有没有办法获得当前季度当天的数量?

所以现在,8月5日,它是第三季度的第36天.

如果没有标准的计算方法,那么有没有人(最好是基于PHP的)算法有用吗?

小智 72

怎么样:

$curMonth = date("m", time());
$curQuarter = ceil($curMonth/3);
Run Code Online (Sandbox Code Playgroud)

瞧瞧:-)

  • 它正在上升,因为人们来这里寻找数学公式来找出季度 (19认同)
  • 我真的不明白为什么这个答案收到了这么多的赞成,因为它根本没有回答这个问题 - 它只是找到了那个不是问题的季度 (9认同)

Cha*_*son 15

我用以下方法编写了一个类.请享用.

public static function getQuarterByMonth($monthNumber) {
  return floor(($monthNumber - 1) / 3) + 1;
}

public static function getQuarterDay($monthNumber, $dayNumber, $yearNumber) {
  $quarterDayNumber = 0;
  $dayCountByMonth = array();

  $startMonthNumber = ((self::getQuarterByMonth($monthNumber) - 1) * 3) + 1;

  // Calculate the number of days in each month.
  for ($i=1; $i<=12; $i++) {
    $dayCountByMonth[$i] = date("t", strtotime($yearNumber . "-" . $i . "-01"));
  }

  for ($i=$startMonthNumber; $i<=$monthNumber-1; $i++) {
    $quarterDayNumber += $dayCountByMonth[$i];
  }

  $quarterDayNumber += $dayNumber;

  return $quarterDayNumber;
}

public static function getCurrentQuarterDay() {
  return self::getQuarterDay(date('n'), date('j'), date('Y'));
}
Run Code Online (Sandbox Code Playgroud)


Mik*_*ike 10

function date_quarter()
{
    return ceil(date('n', time()) / 3);
}
Run Code Online (Sandbox Code Playgroud)

要么

function date_quarter()
{
    $month = date('n');

    if ($month <= 3) return 1;
    if ($month <= 6) return 2;
    if ($month <= 9) return 3;

    return 4;
}
Run Code Online (Sandbox Code Playgroud)


Eel*_*Bos 5

您可以使用Carbon,它具有 getFirstOf{Month,Year,Quarter}() 的简单修饰符

<?php
//take current date
$now = Carbon\Carbon::now();

//modify a copy of it to the first day of the current quarter
$firstOfQuarter = $now->copy()->firstOfQuarter();

//calculate the difference in days and add 1 to correct the index
$dayOfQuarter = $now->diffInDays($firstOfQuarter) + 1;
Run Code Online (Sandbox Code Playgroud)