Adding days to $Date in PHP

2018-12-31 20:03发布

I have a date returned as part of a mySQL query in the form 2010-09-17

I would like to set the variables $Date2 to $Date5 as follows:

$Date2 = $Date + 1

$Date3 = $Date + 2

etc..

so that it returns 2010-09-18, 2010-09-19 etc...

I have tried

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

but this gives me the date BEFORE $Date.

What is the correct way to get my Dates in the format form 'Y-m-d' so that they may be used in another query?

标签: php date
9条回答
怪性笑人.
2楼-- · 2018-12-31 20:23

Here is a small snippet to demonstrate the date modifications:

$date = date("Y-m-d");
//increment 2 days
$mod_date = strtotime($date."+ 2 days");
echo date("Y-m-d",$mod_date) . "\n";

//decrement 2 days
$mod_date = strtotime($date."- 2 days");
echo date("Y-m-d",$mod_date) . "\n";

//increment 1 month
$mod_date = strtotime($date."+ 1 months");
echo date("Y-m-d",$mod_date) . "\n";

//increment 1 year
$mod_date = strtotime($date."+ 1 years");
echo date("Y-m-d",$mod_date) . "\n";
查看更多
情到深处是孤独
3楼-- · 2018-12-31 20:24

If you're using PHP 5.3, you can use a DateTime object and its add method:

$Date1 = '2010-09-17';
$date = new DateTime($Date1);
$date->add(new DateInterval('P1D')); // P1D means a period of 1 day
$Date2 = $date->format('Y-m-d');

Take a look at the DateInterval constructor manual page to see how to construct other periods to add to your date (2 days would be 'P2D', 3 would be 'P3D', and so on).

Without PHP 5.3, you should be able to use strtotime the way you did it (I've tested it and it works in both 5.1.6 and 5.2.10):

$Date1 = '2010-09-17';
$Date2 = date('Y-m-d', strtotime($Date1 . " + 1 day"));
// var_dump($Date2) returns "2010-09-18"
查看更多
妖精总统
4楼-- · 2018-12-31 20:25

Here has an easy way to solve this.

<?php
   $date = "2015-11-17";
   echo date('Y-m-d', strtotime($date. ' + 5 days'));
?>

Output will be:

2015-11-22

Solution has found from here - How to Add Days to Date in PHP

查看更多
冷夜・残月
5楼-- · 2018-12-31 20:30

From PHP 5.2 on you can use modify with a DateTime object:

http://php.net/manual/en/datetime.modify.php

$Date1 = '2010-09-17';
$date = new DateTime($Date1);
$date->modify('+1 day');
$Date2 = $date->format('Y-m-d');

Be careful when adding months... (and to a lesser extent, years)

查看更多
若你有天会懂
6楼-- · 2018-12-31 20:33

All you have to do is use days instead of day like this:

<?php
$Date = "2010-09-17";
echo date('Y-m-d', strtotime($Date. ' + 1 days'));
echo date('Y-m-d', strtotime($Date. ' + 2 days'));
?>

And it outputs correctly:

2010-09-18
2010-09-19
查看更多
浪荡孟婆
7楼-- · 2018-12-31 20:33

Using a variable for Number of days

$myDate = "2014-01-16";
$nDays = 16;
$newDate = strtotime($myDate . '+ '.$nDays.'days');
echo newDate('d/m/Y', $soma); //format new date 
查看更多
登录 后发表回答