views:

1402

answers:

4

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 number of the current day of the current quarter?

So right now, August 5, it is day 36 of the third quarter.

If there is no standard way of calculating this, does anyone have a (prefereably PHP-based) algorithm handy?

A: 

Why not just mod the day of the year with 92?

$quarter=date('z')%92;
scompt.com
Because quarters don't have equal length: Jan + Feb + Mar = 31 + 28 + 31 = 90 (not even considering leap years)
balpha
Because months don't fall on that boundary. For example with Feb having 28 or 29 days, the first quarter has 89 or 90 days.
Jason Cohen
A: 

Assuming you mean a calendar-quarter (because a company fiscal year can start in any month of the year), you could rely on the date('z') to determine the day-of-year, and then keep a simple array of the day each quarter starts on:

$quarterStartDays = array( 1 /* Jan 1 */, 90 /* Mar 1, non leap-year */, ... );

Then with the current day-of-year you can first locate the largest start-day that's less than or equal to the day-of-year, then subtract.

Note that you need different numbers depending on the leap year.

Jason Cohen
+1  A: 

I wrote a class with the following methods. Enjoy.

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'));
}
Chad Johnson
+1  A: 
<?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";
?>
scompt.com