2009-08-05 6 views
17

PHP proporciona formas de obtener el número del día actual del mes (fecha ('j')) así como también el número del día actual del año (fecha ('z')). ¿Hay alguna forma de obtener el número del día actual del trimestre actual?¿Forma fácil de obtener el número del día del trimestre actual?

Así que ahora, 5 de agosto, es el día 36 del tercer trimestre.

Si no hay una forma estándar de calcular esto, ¿alguien tiene un algoritmo (preferiblemente basado en PHP) a mano?

+0

¿Cómo se define "quarter"? –

+0

Un grupo de tres meses. –

+1

Pseudocódigo: day_of_quarter (y, m, d) = day_of_year (y, m, d) - day_of_year (y, 3 * ((m-1)% 3) + 1, 1) + 1 – balpha

Respuesta

11

Escribí una clase con los siguientes métodos. Disfrutar.

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')); 
} 
1

Suponiendo que se refiera a un trimestre calendario (porque un año fiscal de la compañía puede comenzar en cualquier mes del año), puede confiar en la fecha ('z') para determinar el día del año y luego una matriz simple del día cada trimestre comienza el:

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

luego, con el actual día de año por primera vez puede localizar el más grande de puesta en día que es menor o igual al día de año, a continuación, sustraer.

Tenga en cuenta que necesita diferentes números en función del año bisiesto.

1
<?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"; 
?> 
49

¿Qué tal:

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

Et voila :-)

+9

Realmente no puedo entender por qué esta respuesta ha recibido tantos upvotes, ya que no está respondiendo la pregunta en absoluto - es simplemente encontrar el trimestre que no era la pregunta – DHS

+15

Se está levantando votos porque la gente viene aquí mientras busca una fórmula matemática para averiguar el trimestre – LucasSeveryn

+1

Esta respuesta debería ser un comentario. – mickmackusa

6
function date_quarter() 
{ 
    return ceil(date('n', time())/3); 
} 

o

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

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

    return 4; 
} 
0

Usted puede utilizar Carbon tiene modificadores fáciles para getFirstOf {Mes, Año, Trimestre}()

<?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; 
0
<?php 

function trimester_day($time = null) { 
    $time = $time ? intval($time) : time(); 
    $date = intval(date("j", $time)); 
    $month = intval(date("n", $time)); 
    $year = intval(date("Y", $time)); 
    // get the selected quarter as number between 1 and 4 
    $quarter = ceil($month/3); 
    // get the first month of current quarter in n format 
    $fmonth = $quarter + (($quarter - 1) * 2); 
    // map days in a year by month 
    $map = [31,28,31,30,31,30,31,31,30,31,30,31]; 
    // check if is leap year 
    if (((($year % 4) == 0) && ((($year % 100) != 0) || (($year % 400) == 0)))) { 
     $map[1] = 29; 
    } 
    // get total number of days in selected quarter, by summing the relative portion of $map array 
    $total = array_sum(array_slice($map, ($fmonth - 1), 3)); 
    // get number of days passed in selected quarter, by summming the relative portion of $map array 
    $map[$month-1] = $date; 
    $day = array_sum(array_slice($map, ($fmonth - 1), ($month - $fmonth + 1))); 
    // return 
    return "Day number " . $day . " on " . $total . " of quarter " . $quarter . ", $year."; 
} 

$time = strtotime("2017-01-01"); // return Day number 1 on 90 of quarter 1, 2017. 
$time = strtotime("2017-04-01"); // return Day number 1 on 91 of quarter 2, 2017. 
$time = strtotime("2017-08-15"); // return Day number 46 on 92 of quarter 3, 2017. 
$time = strtotime("2017-12-31"); // return Day number 92 on 92 of quarter 4, 2017. 

echo trimester_day($time) . "\n"; 
+0

Debe proporcionar algunos ejemplos de entrada y salida, así como una explicación de su código, en lugar de solo descargar la fuente sin procesar. –

+0

Gracias, el código fue bastante auto explicativo, pero aquí tienes. –

0

tenemos que calcular la fecha del primer trimestre primera

$current_month = date('m'); 

// Get first month of quarter 
$new_month = (3 * floor(($current_month - 1)/3)) + 1; 

// Add prefix zero if needed 
$new_month = substr('0' . $new_month, -2); 

$first_quarter_day_date = date('Y') . '-' . $new_month . '-01'; 

siguiente se calcula el http://php.net/manual/en/datetime.diff.php

$datetime1 = new DateTime($first_quarter_day_date); 
$datetime2 = new DateTime(); 

$interval = $datetime1->diff($datetime2); 
echo $interval->format('%a days'); 
Cuestiones relacionadas