PHP - How to get start date and end date from given week number and year

PHP - How to get start date and end date from given week number and year

In this PHP tutorial, I will tell you how to get start date and end date from week number and year.

We will calculate ISO week number (1-53) and represent the start of the week "Monday".

There is a setISODate() method with DateTime extension that accepts the year (4-digit year) and ISO week number.

Get start and end date from week number
  1. <?php
  2. $week=29;
  3. $year=2017;
  4. function getStartAndEndDate($week, $year) {
  5. $dateTime = new DateTime();
  6. $dateTime->setISODate($year, $week);
  7. $result['start_date'] = $dateTime->format('d-M-Y');
  8. $dateTime->modify('+6 days');
  9. $result['end_date'] = $dateTime->format('d-M-Y');
  10. return $result;
  11. }
  12. $dates=getStartAndEndDate($week,$year);
  13. print_r($dates);
  14. ?>

If you run above code then you will get following output :

Array
(
    [start_date] => 17-Jul-2017
    [end_date] => 23-Jul-2017
)
Get date from week number
  1. <?php
  2. $week=29;
  3. $year=2017;
  4. $timestamp = mktime( 0, 0, 0, 1, 1, $year ) + ( $week * 7 * 24 * 60 * 60 );
  5. $timestampForMonday = $timestamp - 86400 * ( date( 'N', $timestamp ) - 1 );
  6. $dateForMonday = date( 'd-M-Y', $timestampForMonday );
  7. echo $dateForMonday;
  8. ?>

Output :

17-Jul-2017
Get start and end date from week number using Carbon

If you have installed carbon extension then you can use following code to get same output :

  1. <?php
  2. $week=29;
  3. $year=2017;
  4. $date = \Carbon\Carbon::now();
  5. $date->setISODate($year,$week);
  6. echo $date->startOfWeek();
  7. echo $date->endOfWeek();
  8. ?>

Phone: (+91) 8800417876
Noida, 201301
ataşehir escort maltepe escort bostancı escort kadıköy escort maltepe escort ataşehir escort kurtköy escort kartal escort pendik escort ataşehir escort
şişli escort
pendik escort
izmir escort izmir escort izmir escort izmir escort denizli escort antalya escort antalya escort antalya escort izmir escort izmir escort izmir escort izmir escort izmir escort