40

I need to calculate the timestamp of exactly 7 days ago using PHP, so if it's currently March 25th at 7:30pm, it would return the timestamp for March 18th at 7:30pm.

Should I just subtract 604800 seconds from the current timestamp, or is there a better method?

Mike Crittenden
  • 5,779
  • 6
  • 47
  • 74

6 Answers6

88
strtotime("-1 week")
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
27

strtotime is your friend

echo strtotime("-1 week");
Ben Everard
  • 13,652
  • 14
  • 67
  • 96
11

http://php.net/strtotime

echo strtotime("-1 week");
Aaron W.
  • 9,254
  • 2
  • 34
  • 45
9

There is the following example on PHP.net

<?php
  $nextWeek = time() + (7 * 24 * 60 * 60);
               // 7 days; 24 hours; 60 mins; 60secs
  echo 'Now:       '. date('Y-m-d') ."\n";
  echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
  // or using strtotime():
  echo 'Next Week: '. date('Y-m-d', strtotime('+1 week')) ."\n";
?>

Changing + to - on the first (or last) line will get what you want.

Luís Guilherme
  • 2,620
  • 6
  • 26
  • 41
4

From PHP 5.2 you can use DateTime:

$timestring="2015-03-25";
$datetime=new DateTime($timestring);
$datetime->modify('-7 day');
echo $datetime->format("Y-m-d"); //2015-03-18

Instead of creating DateTime with string, you can setTimestamp directly on object:

$timestamp=1427241600;//2015-03-25
$datetime=new DateTime();
$datetime->setTimestamp($timestamp);
$datetime->modify('-7 day');
echo $datetime->format("Y-m-d"); //2015-03-18
Paweł Tomkiel
  • 1,974
  • 2
  • 21
  • 39
0
<?php 
   $before_seven_day = $date_timestamp - (7 * 24 * 60 * 60)
   // $date_timestamp is the date from where you found to find out the timestamp.
?>

you can also use the string to time function for converting the date to timestamp. like

strtotime(23-09-2013);
Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
Navdeep Singh
  • 403
  • 4
  • 5