php arrays date week-number

Obtener el número de semana en el mes a partir de la fecha en PHP?



arrays date (12)

Tengo una serie de fechas aleatorias (que no provienen de MySQL). Necesito agruparlos por semana como Semana1, Semana2, y así hasta Semana5.

Lo que tengo es esto:

$dates = array(''2015-09-01'',''2015-09-05'',''2015-09-06'',''2015-09-15'',''2015-09-17'');

Lo que necesito es una función para obtener el número de semana del mes al proporcionar la fecha.

Sé que puedo obtener el número de semana haciendo date(''W'',strtotime(''2015-09-01'')); pero el número de esta semana es el número entre el año (1-52) pero solo necesito el número de semana del mes, por ejemplo, en septiembre de 2015 hay 5 semanas:

  • Semana1 = 1ro a 5to
  • Semana2 = 6 a 12
  • Semana3 = 13 a 19
  • Semana 4 = 20 a 26
  • Semana5 = 27 a 30

Debería poder obtener la semana Semana1 simplemente proporcionando la fecha, por ejemplo

$weekNumber = getWeekNumber(''2015-09-01'') //output 1; $weekNumber = getWeekNumber(''2015-09-17'') //output 3;


Creo que esta relación debería ser cierta y ser útil:

Week of the month = Week of the year - Week of the year of first day of month + 1

Implementado en PHP obtienes esto:

function weekOfMonth($date) { //Get the first day of the month. $firstOfMonth = strtotime(date("Y-m-01", $date)); //Apply above formula. return intval(date("W", $date)) - intval(date("W", $firstOfMonth)) + 1; }

Para obtener semanas que comienzan con el domingo, simplemente reemplace ambas date("W", ...) con strftime("%U", ...) .


Dado el time_t wday (0 = domingo a 6 = sábado) del primero del mes en firstWday , esto devuelve el número de semana (basado en domingo) dentro del mes:

weekOfMonth = floor((dayOfMonth + firstWday - 1)/7) + 1

Traducido al PHP:

function weekOfMonth($dateString) { list($year, $month, $mday) = explode("-", $dateString); $firstWday = date("w",strtotime("$year-$month-1")); return floor(($mday + $firstWday - 1)/7) + 1; }


Hay muchas soluciones, pero aquí hay una solución que funciona bien en la mayoría de los casos.

//It''s easy, no need to use php function //Let''s say your date is 2017-07-02 $Date = explode("-","2017-07-02"); $DateNo = $Date[2]; $WeekNo = $DateNo / 7; // devide it with 7 if(is_float($WeekNo) == true) { $WeekNo = ceil($WeekNo); //So answer will be 1 } //If value is not float then ,you got your answer directly

Acepta la marca de tiempo de Unix, la fecha normal o devuelve la semana actual desde la time() si no pasa ningún valor.

¡Disfrutar!


He creado esta función por mi cuenta, lo que parece funcionar correctamente. En caso de que alguien más tenga una mejor manera de hacerlo, comparta ... Esto es lo que he hecho.

function weekOfMonth($qDate) { $dt = strtotime($qDate); $day = date(''j'',$dt); $month = date(''m'',$dt); $year = date(''Y'',$dt); $totalDays = date(''t'',$dt); $weekCnt = 1; $retWeek = 0; for($i=1;$i<=$totalDays;$i++) { $curDay = date("N", mktime(0,0,0,$month,$i,$year)); if($curDay==7) { if($i==$day) { $retWeek = $weekCnt+1; } $weekCnt++; } else { if($i==$day) { $retWeek = $weekCnt; } } } return $retWeek; }


echo weekOfMonth(''2015-09-08'') // gives me 2;


La forma central es

function weekOfMonth($date) { $firstOfMonth = date("Y-m-01", strtotime($date)); return intval(date("W", strtotime($date))) - intval(date("W", strtotime($firstOfMonth))); }


Mi funcion La idea principal: contaríamos la cantidad de semanas transcurridas desde la primera fecha del mes hasta la actual. Y el número de la semana actual sería el próximo. Funciona según la regla: "La semana comienza desde el lunes" (para el tipo basado en domingo necesitamos transformar el algoritmo creciente)

function GetWeekNumberOfMonth ($date){ echo $date -> format(''d.m.Y''); //define current year, month and day in numeric $_year = $date -> format(''Y''); $_month = $date -> format(''n''); $_day = $date -> format(''j''); $_week = 0; //count of weeks passed for ($i = 1; $i < $_day; $i++){ echo "/n/n-->"; $_newDate = mktime(0,0,1, $_month, $i, $_year); echo "/n"; echo date("d.m.Y", $_newDate); echo "-->"; echo date("N", $_newDate); //on sunday increasing weeks passed count if (date("N", $_newDate) == 7){ echo "New week"; $_week += 1; } } return $_week + 1; // as we are counting only passed weeks the current one would be on one higher } $date = new DateTime("2019-04-08"); echo "/n/nResult: ". GetWeekNumberOfMonth($date);


Puede usar la función a continuación, completamente comentada:

/** * Returns the number of week in a month for the specified date. * * @param string $date * @return int */ function weekOfMonth($date) { // estract date parts list($y, $m, $d) = explode(''-'', date(''Y-m-d'', strtotime($date))); // current week, min 1 $w = 1; // for each day since the start of the month for ($i = 1; $i <= $d; ++$i) { // if that day was a sunday and is not the first day of month if ($i > 1 && date(''w'', strtotime("$y-$m-$i")) == 0) { // increment current week ++$w; } } // now return return $w; }


También puedes usar esta fórmula simple para encontrar la semana del mes

$currentWeek = ceil((date("d",strtotime($today_date)) - date("w",strtotime($today_date)) - 1) / 7) + 1;

ALGORITMO

Fecha = ''2018-08-08'' => Ymd

  1. Averigüe el día del mes, por ejemplo. 08
  2. Averigüe Representación numérica del día de la semana menos 1 (número de días en la semana), por ejemplo. (3-1)
  3. Tome la diferencia y almacene en el resultado
  4. Resta 1 del resultado
  5. Divídalo por 7 para dar como resultado y limite el valor del resultado
  6. Agregue 1 al resultado, por ejemplo. techo ((08 - 3) - 1) / 7) + 1 = 2

// self::DAYS_IN_WEEK = 7; function getWeeksNumberOfMonth(): int { $currentDate = new /DateTime(); $dayNumberInMonth = (int) $currentDate->format(''j''); $dayNumberInWeek = (int) $currentDate->format(''N''); $dayNumberToLastSunday = $dayNumberInMonth - $dayNumberInWeek; $daysCountInFirstWeek = $dayNumberToLastSunday % self::DAYS_IN_WEEK; $weeksCountToLastSunday = ($dayNumberToLastSunday - $daysCountInFirstWeek) / self::DAYS_IN_WEEK; $weeks = []; array_push($weeks, $daysCountInFirstWeek); for ($i = 0; $i < $weeksCountToLastSunday; $i++) { array_push($weeks, self::DAYS_IN_WEEK); } array_push($weeks, $dayNumberInWeek); if (array_sum($weeks) !== $dayNumberInMonth) { throw new Exception(''Logic is not valid''); } return count($weeks); }

Variante corta:

(int) (new /DateTime())->format(''W'') - (int) (new /DateTime(''first day of this month''))->format(''W'') + 1;


function getWeekOfMonth(DateTime $date) { $firstDayOfMonth = new DateTime($date->format(''Y-m-1'')); return ceil(($firstDayOfMonth->format(''N'') + $date->format(''j'') - 1) / 7); }

La solución Goendg no funciona para 2016-10-31.


function weekOfMonth($strDate) { $dateArray = explode("-", $strDate); $date = new DateTime(); $date->setDate($dateArray[0], $dateArray[1], $dateArray[2]); return floor((date_format($date, ''j'') - 1) / 7) + 1; }

weekOfMonth (''2015-09-17'') // devuelve 3


//It''s easy, no need to use php function //Let''s say your date is 2017-07-02 $Date = explode("-","2017-07-02"); $DateNo = $Date[2]; $WeekNo = $DateNo / 7; // devide it with 7 if(is_float($WeekNo) == true) { $WeekNo = ceil($WeekNo); //So answer will be 1 } //If value is not float then ,you got your answer directly