PHP获取一年有几周以及每周开始日期和结束日期

这篇文章主要介绍php计算一年有多少周,获取每周开始日期和结束日期,有需要的朋友可以参考一下。

最近接了一个项目,其中有一需求是用php获取一年有几周以及每周开始日期和接触日期。在网上找些资料没有合适的,于是自己做了一份,下面通过两种方式实现PHP获取一年有几周以及每周开始日期和结束日期。

代码一:

  1. <?php
  2. header("Content-type:text/html;charset=utf-8");
  3. date_default_timezone_set("Asia/Shanghai");
  4. $year = (int)$_GET['year'];
  5. $week = (int)$_GET['week'];
  6. $weeks = date("W", mktime(0, 0, 0, 12, 28, $year));
  7. echo $year . '年一共有' . $weeks . '周<br />';
  8. if ($week > $weeks || $week <= 0)
  9. {
  10. $week = 1;
  11. }
  12. if ($week < 10)
  13. {
  14. $week = '0' . $week;
  15. }
  16. $timestamp['start'] = strtotime($year . 'W' . $week);
  17. $timestamp['end'] = strtotime('+1 week -1 day', $timestamp['start']);
  18. echo $year . '年第' . $week . '周开始时间戳:' . $timestamp['start'] . '<br />';
  19. echo $year . '年第' . $week . '周结束时间戳:' . $timestamp['end'] . '<br />';
  20. echo $year . '年第' . $week . '周开始日期:' . date("Y-m-d", $timestamp['start']) . '<br />';
  21. echo $year . '年第' . $week . '周结束日期:' . date("Y-m-d", $timestamp['end']);
  22. ?>

代码二:

  1. <?php
  2. header("Content-type:text/html;charset=utf-8");
  3. function getIsoWeeksInYear($year)
  4. {
  5. $date = new DateTime;
  6. $date->setISODate($year, 53);
  7. return ($date->format("W") === "53" ? 53 : 52);
  8. }
  9. function weekday($custom_date)
  10. {
  11. $week_start = date('d-m-Y', strtotime('this week monday', $custom_date));
  12. $week_end = date('d-m-Y', strtotime('this week sunday', $custom_date));
  13. $week_array[0] = $week_start;
  14. $week_array[1] = $week_end;
  15. return $week_array;
  16. }
  17. echo '<br> Weeks in 2013<br>' . getIsoWeeksInYear(2013);
  18. $weekday = weekday(strtotime(date('d-m-Y', strtotime('5-8-2013'))));
  19. echo '<br> 10-8-2013';
  20. echo '<br>Start: ' . $weekday[0];
  21. echo '<br>End: ' . $weekday[1];
  22. ?>

以上本文的全部内容,希望对大家学习PHP获取一年有几周以及每周开始日期和结束日期,有所帮助。