code_junkie

how to get the date of last week's (tuesday or any other day) in php

Nov 14th, 2011
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. $tuesday = strtotime('last Tuesday');
  2. // check if we need to go back in time one more week
  3. $tuesday = date('W', $tuesday)==date('W') ? $tuesday-7*86400 : $tuesday;
  4.  
  5. $tuesday = date('W', $tuesday)==date('W') ? $tuesday-7*86400+7200 : $tuesday;
  6.  
  7. echo strtotime('last Tuesday');
  8.  
  9. $z = date("Y-m-d", strtotime("last Saturday"));
  10. $z = (date('W', strtotime($z)) == date('W')) ? (strtotime($z)-7*86400+7200) : strtotime($z);
  11. print date("Y-m-d", $z);
  12.  
  13. // test: find last date for each day of the week
  14. foreach (array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun') as $day) {
  15. print $day . " => " . date('m/d/Y', last_dayofweek($day)) . "n";
  16. }
  17.  
  18. function last_dayofweek($day)
  19. {
  20. // return timestamp of last Monday...Friday
  21. // will return today if today is the requested weekday
  22. $day = strtolower(substr($day, 0, 3));
  23. if (strtolower(date('D')) == $day)
  24. return strtotime("today");
  25. else
  26. return strtotime("last {$day}");
  27. }
Add Comment
Please, Sign In to add comment