get next and previous day with PHP

后端 未结 11 735
悲哀的现实
悲哀的现实 2020-11-28 03:44

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 d

相关标签:
11条回答
  • 2020-11-28 04:14

    Simply use this

    echo date('Y-m-d',strtotime("yesterday"));
    echo date('Y-m-d',strtotime("tomorrow"));
    
    0 讨论(0)
  • 2020-11-28 04:18

    Use

    $time = time();
    

    For previous day -

    date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time)- 1 ,date("Y", $time)));
    

    For 2 days ago

    date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time) -2 ,date("Y", $time)));
    

    For Next day -

    date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time)+ 1 ,date("Y", $time)));
    

    For next 2 days

    date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time) +2 ,date("Y", $time)));
    
    0 讨论(0)
  • 2020-11-28 04:20
    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.

    0 讨论(0)
  • 2020-11-28 04:20

    You could use 'now' as string to get today's/tomorrow's/yesterday's date:

    $previousDay = date('Y-m-d', strtotime('now - 1day'));
    $toDay       = date('Y-m-d', strtotime('now'));
    $nextDay     = date('Y-m-d', strtotime('now + 1day'));
    
    0 讨论(0)
  • 2020-11-28 04:24
    strtotime('-1 day', strtotime($date))
    

    This returns the number of difference in seconds of the given date and the $date.so you are getting wrong result .

    Suppose $date is todays date and -1 day means it returns -86400 as the difference and the when you try using date you will get 1969-12-31 Unix timestamp start date.

    0 讨论(0)
提交回复
热议问题