Pregunta

I'm working on php function that does the math to obtain the week number of the year based on some variables.

Actually, I have 2 variables:

  1. first is a date variable (in the YYYY-MM-DD format);
  2. second is a "day-mark" variable (I have a list of 9 specific days -> 2, 6, 8, 10, 14, 17, 21, 23, 27);

This is the function that I've managed to put together so I can obtain the week of the year:

$duedt = explode("-", "YYYY-MM-DD");
$date = mktime(0, 0, 0, $duedt[1], $duedt[2], $duedt[0]);
$week = (int)date('W', $date); 

As an example for the above code, if we replace "YYYY-MM-DD" with "2014-02-09", it will determine that the week number is 6 (witch is correct)

Now, my question is: How can I modify it, so it will keep track of the second variable (the "day-mark") ?

For the "2014-02-09" day example what I want to have is the following:

  • if the "day-mark" is 10 (meaning the 10th of the month) => the week number will be 7
  • if the "day-mark" is 8 (meaning the 8th of the month) => the week number will be 6

Any ideas on how I can modify the function ?

Thank you in advance!

My best regards, Michael

¿Fue útil?

Solución 2

function week_day_of_month($day,$month_num, $year) {
  $days_in_month = array(1=>31, 2 => 28,...);//doesn't account for leap, you need to
  $ts = strtotime(format_date($day,$month_num,$year));
  $week_num = date('W', $ts);
  $month_days = $days_in_month[$month_num];
  for ($i = 1;$i<=$month_days;$i++) {
    $ats = strtotime(format_date($i,$month_num, $year));
    if ($ats == $ts)
    break;
  }
 $day = $i;
 return array($day,intval($week_num));
}

format_date just turns m,d,y into something strtotime can parse. you can handle leap by having two arrays within days of month 0=> non leap, 1=>leap. calculate leap is easy. and choose the correct array

Otros consejos

I'm not sure if you're over-complicating this or not. Can't you just provide the date and get the week number for any date using the same method? Or even simpler below:

$date = new DateTime('2014-02-08');
echo (int) $date->format('W'); // 6

$date = new DateTime('2014-02-09');
echo (int) $date->format('W'); // 6

$date = new DateTime('2014-02-10');
echo (int) $date->format('W'); // 7
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top