Connect with Expertise | Find Experts, Get Answers, Share Insights

how do i get the first day of the week?

 
Join Date: Oct 2007
Posts: 9
#1: Jan 18 '08
How can I get the first day of the week in php? I probably have to write a function, but i am not good with dates.

I'm looking for a function where you input the week number and the year, and it will return the timestamp of the first sunday of that week.


Thanks in advance!

 
Join Date: Oct 2007
Posts: 9
#2: Jan 18 '08

re: how do i get the first day of the week?


I found this one online but it was posted on a forum from 2003 and times out. I am using php version 5, so I imagine that either this is badly coded or something has been deprecated or doesn't function the way it did at the time this was made. Any suggestions on making it work with php 5?

Expand|Select|Wrap|Line Numbers
  1. function firstDayofWeek($week,$year) 
  2. {
  3.     $timestamp = mktime(0, 0, 0, 1, 1, $year);
  4.     if( $week == 1 ) 
  5.     {
  6.         while ( date("W",$timestamp) < 2 ) 
  7.         {
  8.             $timestamp += (60*60*24);
  9.         }
  10.         $timestamp -= (60*60*24*8);
  11.     }
  12.     else 
  13.     {
  14.         while ( date("W",$timestamp) < $week ) 
  15.         {
  16.             $timestamp += (60*60*24);
  17.         }
  18.         $timestamp -= (60*60*24);
  19.     }
  20.     return $timestamp;
  21. }
 
Join Date: Jan 2008
Posts: 1
#3: Jan 30 '08

re: how do i get the first day of the week?


I'm struggling with same problem, i made something similiar to code that you posted, but it goes wrong when year changes... propably because week 1 sometimes begin in December.

Working piece of code would be highly appreciated :)

Edit: ok, now i found something, that seems to work

Expand|Select|Wrap|Line Numbers
  1.   function getFirstDayOfWeek($year, $weeknr)
  2. {
  3. $offset = date('w', mktime(0,0,0,1,1,$year));
  4. $offset = ($offset < 5) ? 1-$offset : 8-$offset;
  5. $monday = mktime(0,0,0,1,1+$offset,$year);
  6. $date = strtotime('+' . ($weeknr - 1) . ' weeks', $monday);
  7. return date('m/d/Y',$date);
  8. }
This gives monday as first day of week, so you might need to do some changes if you need sunday.
 
Join Date: Sep 2009
Posts: 1
#4: Sep 10 '09

re: how do i get the first day of the week?


Expand|Select|Wrap|Line Numbers
  1. <?php $firstday = strtotime('Last Sunday'); ?>
Reply