Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Year and week to date in php

Tags:

date

php

I have two pieces of information extracted from a MySQL database, the year(2009, 2010, ect) and the week (1-52). And I need to convert it in to a date start and date end..

For example:

Year=2010, Week=1 would be (Friday, Jan 1st, 2010) - (Sunday, Jan 3rd, 2010)
Year=2010, Week=33 would be (Monday, Aug 16th, 2010) - (Sunday, Aug 22nd, 2010)
Year=2010, Week=34 would be (Monday, Aug 23rd, 2010) - (Sunday, Aug 29th, 2010)

How would I go about doing that in php ?

like image 708
Steven Smethurst Avatar asked Aug 19 '10 23:08

Steven Smethurst


People also ask

How to get week and year from date in php?

php $ddate = "2012-10-18"; $duedt = explode("-",$ddate); $date = mktime(0, 0, 0, $duedt[2], $duedt[1],$duedt[0]); $week = (int)date('W', $date); echo "Weeknummer: ".

How to get week from date in php?

$firstday = date ( 'l - d/m/Y' , strtotime ( "this week" ));

How to date format in php?

Change YYYY-MM-DD to DD-MM-YYYY In the below example, we have date 2019-09-15 in YYYY-MM-DD format, and we will convert this to 15-09-2019 in DD-MM-YYYY format. $orgDate = "2019-09-15"; $newDate = date("d-m-Y", strtotime($orgDate));

What is the use of date() function in php?

The date() function formats a local date and time, and returns the formatted date string.


2 Answers

$year = "2010"; // Year 2010
$week = "01"; // Week 1

$date1 = date( "l, M jS, Y", strtotime($year."W".$week."1") ); // First day of week
$date2 = date( "l, M jS, Y", strtotime($year."W".$week."7") ); // Last day of week
echo $date1 . " - " . $date2;

If week number is under 10 then append a 0 before number. 1 won't work, it should be 01.

like image 136
Naveed Avatar answered Oct 22 '22 02:10

Naveed


Since this question and the accepted answer were posted the DateTime classes make this much simpler to do:-

function daysInWeek($weekNum)
{
    $result = array();
    $datetime = new DateTime();
    $datetime->setISODate((int)$datetime->format('o'), $weekNum, 1);
    $interval = new DateInterval('P1D');
    $week = new DatePeriod($datetime, $interval, 6);

    foreach($week as $day){
        $result[] = $day->format('d/m/Y');
    }
    return $result;
}

var_dump(daysInWeek(24));

Output:-

array (size=7)
  0 => string '10/06/2013' (length=10)
  1 => string '11/06/2013' (length=10)
  2 => string '12/06/2013' (length=10)
  3 => string '13/06/2013' (length=10)
  4 => string '14/06/2013' (length=10)
  5 => string '15/06/2013' (length=10)
  6 => string '16/06/2013' (length=10)

This has the added advantage of taking care of leap years etc..

like image 40
vascowhite Avatar answered Oct 22 '22 02:10

vascowhite