fork download
  1. <?php
  2. /*
  3.   その年の第何週かを求める
  4.   */
  5. function get_nth_week($d) {
  6. // その年の 1月1日
  7. $d0 = new DateTime($d->format('Y') . '-1-1');
  8.  
  9. // 1月1日の週の日曜日にする
  10. $d0->sub(new DateInterval('P' . $d0->format('w') . 'D'));
  11.  
  12. // 1月1日の週の日曜日から、何週間離れているか
  13. $diff = ($d->getTimestamp() - $d0->getTimestamp()) / 60 / 60 / 24 / 7;
  14.  
  15. // 整数化
  16. $diff = floor($diff);
  17.  
  18. // ゼロ始まりなので、+1 して返す
  19. return $diff + 1;
  20. }
  21.  
  22.  
  23. // 確認(その1)
  24. $d = new DateTime('now');
  25. $w = get_nth_week($d);
  26. echo $d->format(DateTime::ATOM) . ' ' . $w . ' ' . $d->format('W') . "\n";
  27.  
  28. // 確認(その2):バレンタインデー
  29. $d = new DateTime('2014-2-14');
  30. $w = get_nth_week($d);
  31. echo $d->format(DateTime::ATOM) . ' ' . $w . ' ' . $d->format('W') . "\n";
  32.  
  33. // 確認(その3):去年
  34. $d = new DateTime('2013-2-14');
  35. $w = get_nth_week($d);
  36. echo $d->format(DateTime::ATOM) . ' ' . $w . ' ' . $d->format('W') . "\n";
  37.  
  38. $d = new DateTime('2014-12-30');
  39. $w = get_nth_week($d);
  40. echo $d->format(DateTime::ATOM) . ' ' . $w . ' ' . $d->format('W') . "\n";
  41.  
  42. $d = new DateTime('2013-12-30');
  43. $w = get_nth_week($d);
  44. echo $d->format(DateTime::ATOM) . ' ' . $w . ' ' . $d->format('W') . "\n";
  45.  
  46. $d = new DateTime('2012-12-30');
  47. $w = get_nth_week($d);
  48. echo $d->format(DateTime::ATOM) . ' ' . $w . ' ' . $d->format('W') . "\n";
  49.  
  50. ?>
  51.  
  52.  
Success #stdin #stdout 0.01s 20520KB
stdin
Standard input is empty
stdout
2014-06-22T19:44:45+00:00   26 25
2014-02-14T00:00:00+00:00   7 07
2013-02-14T00:00:00+00:00   7 07
2014-12-30T00:00:00+00:00   53 01
2013-12-30T00:00:00+00:00   53 01
2012-12-30T00:00:00+00:00   53 52