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.
- <?php
- $week=29;
- $year=2017;
- function getStartAndEndDate($week, $year) {
- $dateTime = new DateTime();
- $dateTime->setISODate($year, $week);
- $result['start_date'] = $dateTime->format('d-M-Y');
- $dateTime->modify('+6 days');
- $result['end_date'] = $dateTime->format('d-M-Y');
- return $result;
- }
- $dates=getStartAndEndDate($week,$year);
- print_r($dates);
- ?>
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
- <?php
- $week=29;
- $year=2017;
- $timestamp = mktime( 0, 0, 0, 1, 1, $year ) + ( $week * 7 * 24 * 60 * 60 );
- $timestampForMonday = $timestamp - 86400 * ( date( 'N', $timestamp ) - 1 );
- $dateForMonday = date( 'd-M-Y', $timestampForMonday );
- echo $dateForMonday;
- ?>
Output :
17-Jul-2017Get 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 :
- <?php
- $week=29;
- $year=2017;
- $date = \Carbon\Carbon::now();
- $date->setISODate($year,$week);
- echo $date->startOfWeek();
- echo $date->endOfWeek();
- ?>