Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advancing through relative dates using strtotime()

I'm trying to use strtotime() to respond to a button click to advance -1 and +1 days (two buttons) relative to the day advanced to on the previous click.

Example:

  • It's the 10th of the month, I click "-1 day" button, and now the date reads as the 9th.
  • I click the "-1 day" button again and now the readout states the 8th day.
  • I click the "+1 day" button and now the readout states it's the 9th.

I understand the buttons and the displaying the date and using $_GET and PHP to pass info, but how do I get strtotime() to work on the relative date from the last time the time travel script was called?

My work so far has let me show yesterday and today relative to now but not relative to, for example, the day before yesterday, or the day after tomorrow. Or if I use my "last monday" button, the day before or after whatever that day is.

like image 984
kevtrout Avatar asked Aug 12 '08 11:08

kevtrout


2 Answers

Working from previous calls to the same script isn't really a good idea for this type of thing.

What you want to do is always pass two values to your script, the date, and the movement. (the below example is simplified so that you only pass the date, and it will always add one day to it)

Example

http://www.site.com/addOneDay.php?date=1999-12-31

<?php
   echo Date("Y-m-d",(strtoTime($_GET[date])+86400));
?>

Please note that you should check to make sure that isset($_GET[date]) before as well

If you really want to work from previous calls to the same script, you're going to have to do it with sessions, so please specify if that is the case.

like image 98
Issac Kelly Avatar answered Sep 27 '22 02:09

Issac Kelly


Kevin, you work off a solid absolute base (i.e. a date / time), not a relative time period. You then convert to the relative time periods. So, for example, by default, if you were showing a calendar, you'd work from todays date.

int strtotime  ( string $time  [, int $now  ] )

You can see in the function definition here of strtotime, the second argument is now, i.e. you can change the date from which it's relative.

This might be easier to display through a quick loop

This will loop through the last 10 days using "yesterday" as the first argument. We then use date to print it out.

$time = time();

for ($i = 0; $i < 10; $i++) {
    $time = strtotime("yesterday", $time);
    print date("r", $time) . "\n";
}

So pass the time/date in via the URI so you can save the relative date.

like image 31
Philip Reynolds Avatar answered Sep 23 '22 02:09

Philip Reynolds