Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get next and previous day with PHP

Tags:

date

php

I have got two arrows set up, click for next day, next two days, soon and previous day, two days ago, soon. the code seem not working? as it only get one next and previous day.

<a href="home.php?date=<?= date('Y-m-d', strtotime('-1 day', strtotime($date))) ?>" class="prev_day" title="Previous Day" ></a>  <a href="home.php?date=<?= date('Y-m-d', strtotime('+1 day', strtotime($date))) ?>" class="next_day" title="Next Day" ></a> 

is there a way if i click the next button, the date will continously change for the next day. for a moment it will only get one day ahead

like image 502
tonoslfx Avatar asked May 04 '11 12:05

tonoslfx


People also ask

How can I get tomorrow day in PHP?

$newDate = date('Y-m-d', strtotime('tomorrow')); echo $newDate; ?>

How to get day month and year from date in php?

$dateValue = '2012-01-05'; $yeararray = explode("-", $dateValue); echo "Year : ". $yeararray[0]; echo "Month : ". date( 'F', mktime(0, 0, 0, $yeararray[1])); Usiong explode() this can be done.


2 Answers

date('Y-m-d', strtotime('+1 day', strtotime($date))) 

Should read

date('Y-m-d', strtotime(' +1 day')) 

Update to answer question asked in comment about continuously changing the date.

<?php $date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d'); $prev_date = date('Y-m-d', strtotime($date .' -1 day')); $next_date = date('Y-m-d', strtotime($date .' +1 day')); ?>  <a href="?date=<?=$prev_date;?>">Previous</a> <a href="?date=<?=$next_date;?>">Next</a> 

This will increase and decrease the date by one from the date you are on at the time.

like image 81
Alan Whitelaw Avatar answered Sep 29 '22 23:09

Alan Whitelaw


Requirement: PHP 5 >= 5.2.0

You should make use of the DateTime and DateInterval classes in Php, and things will turn to be very easy and readable.

Example: Lets get the previous day.

// always make sure to have set your default timezone date_default_timezone_set('Europe/Berlin');  // create DateTime instance, holding the current datetime $datetime = new DateTime();  // create one day interval $interval = new DateInterval('P1D');  // modify the DateTime instance $datetime->sub($interval);  // display the result, or print_r($datetime); for more insight  echo $datetime->format('Y-m-d');   /**  * TIP: * if you dont want to change the default timezone, use * use the DateTimeZone class instead. * * $myTimezone = new DateTimeZone('Europe/Berlin'); * $datetime->setTimezone($myTimezone);  * * or just include it inside the constructor  * in this form new DateTime("now",   $myTimezone); */ 

References: Modern PHP, New Features and Good Practices By Josh Lockhart

like image 33
Erald Karakashi Avatar answered Sep 30 '22 01:09

Erald Karakashi