php datetime add 1 day
DateTime::add
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
Description
Adds the specified DateInterval object to the specified DateTime object.
Parameters
Return Values
Returns the DateTime object for method chaining or false on failure.
Examples
Example #1 DateTime::add() example
The above examples will output:
Example #2 Further DateTime::add() examples
The above example will output:
Example #3 Beware when adding months
= new DateTime ( ‘2000-12-31’ );
$interval = new DateInterval ( ‘P1M’ );
The above example will output:
See Also
User Contributed Notes 12 notes
Another simple solution to adding a month but not autocorrecting days to the next month is this.
(Also works for substracting months)
$dt = new DateTime(«2016-01-31»);
Hope this helps someone.
Here is a solution to adding months when you want 2014-10-31 to become 2014-11-30 instead of 2014-12-01.
/**
* Class MyDateTime
*
* Extends DateTime to include a sensible addMonth method.
*
* This class provides a method that will increment the month, and
* if the day is greater than the last day in the new month, it
* changes the day to the last day of that month. For example,
* If you add one month to 2014-10-31 using DateTime::add, the
* result is 2014-12-01. Using MyDateTime::addMonth the result is
* 2014-11-30.
*/
class MyDateTime extends DateTime
<
If you need add() and sub() that don’t modify object values, you can create new methods like this:
class DateTimeEnhanced extends DateTime <
$interval = DateInterval :: createfromdatestring ( ‘+1 day’ );
If you use fraction of seconds, you may have surprises. It only occurs when the sum of the floating point parts results in exactly 1 second (0.5 + 0.5 ou 0.3 + 0.7, for example). See these cases at intervals slightly bigger than 1 second:
To resolve, add 1 second to the interval and f property must be negative (-1.0 plus original value):
What you can do with this function/method is a great example of the philosophy: «just because you can do it doesn’t mean you should». I’m talking about two issues: (1) the number of days in the month which varies from months 1-12 as well as for month 2 which could be leap year (or not); and then issue (2): what if there is the need to specify a large quantity of an interval such that it needs to be re-characterized into broader-scoped intervals (i.e. 184 seconds ==> 3 minutes-4 seconds). Examples in notes elsewhere in the docs for this function illustrate both issues and their undesired effects so I won’t focus on them further. But how did I decide to handle? I’ve gone with four «public» functions and a single «private» function, and without giving you a bunch of code to study, here are their summaries.
**Results/goals.
—any number of days/hours/minutes/seconds can be passed in to add/subtractTime and all of «Y/M/D/H/M/S» values get adjusted as you would expect.
—using adjustYear/Month lets you pass +/- values and only «Y/M» values get modified without having undesirable effects on day values.
—a call to the «recharacterize» function helps ensure proper and desired values are in the intervals prior to calling date_add to let it do its work.
/* results:
1383458399 1383458399 2013-11-03 01:59:59 EDT
1383458400 1383462000 2013-11-03 02:00:00 EST
noticed how the second column went from 1383458399 to 1383462000 even though only 1 second was added?
*/
$TodaySQL = substr(date(DATE_ISO8601 ),0,10)
$LastYearSQL = date(‘Y.m.d’,strtotime(«-1 years»))
$NextMonthEndSQL = date(‘Y.m.d’,strtotime(«+1 months»))
// handy little SQL date formats
//Today
2021-03-24
//Last year
2020.03.24
//Next month
2021.04.24
Remark, that calculations on date are not defined as bijective operations. The Summertime is integrated by mixing two concepts. You should test it beforehead.
Datetime will correct a date after each summation, if a date (29.2.2021 => 1.3.2021) or a datetime (29.3.2020 2:30 am (Europe/Berlin) => 29.3.2020 3:30 or 29.3.2020 1:30)
Be careful when using this function, I may have happened upon a bug in PHP7.
My code is as follows
//get date from post or else fill with today’s date
if (isset($_POST[«from»]))
<
$from = date_create($_POST[«from»]);
>else<
$from = date_create(date(«Y-m-d»));
>
The resultant output is
$from = 2015-12-11
$to = 2015-12-11
In actuality the result should be
$from = 2015-12-10
$to = 2015-12-11
to fix this i needed to change the code to
//get date from post or else fill with today’s date
if (isset($_POST[«from»]))
<
$from = date_create($_POST[«from»]);
>else<
$from = date_create(date(«Y-m-d»));
>
This isn’t strictly the code I wanted. Possible bug?
Adding one day to a date
My code to add one day to a date returns a date before day adding: 2009-09-30 20:24:00 date after adding one day SHOULD be rolled over to the next month: 1970-01-01 17:33:29
I have used pretty similar code before, what am I doing wrong here?
12 Answers 12
For PHP 5.2.0+, you may also do as follows:
It Worked for me: For Current Date
Simple to read and understand way:
The modify() method that can be used to add increments to an existing DateTime value.
Create a new DateTime object with the current date and time:
Once you have the DateTime object, you can manipulate its value by adding or subtracting time periods:
You can read more on the PHP Manual.
I always just add 86400 (seconds in a day):
It’s not the slickest way you could probably do it, but it works!
While I agree with Doug Hays’ answer, I’ll chime in here to say that the reason your code doesn’t work is because strtotime() expects an INT as the 2nd argument, not a string (even one that represents a date)
If you turn on max error reporting you’ll see this as a «A non well formed numeric value» error which is E_NOTICE level.
The following code get the first day of January of current year (but it can be a another date) and add 365 days to that day (but it can be N number of days) using DateTime class and its method modify() and format():
Since you already have an answer to what’s wrong with your code, I can bring another perspective on how you can play with datetimes generally, and solve your problem specifically.
Oftentimes you find yourself posing a problem in terms of solution. This is just one of the reasons you end up with an imperative code. It’s great if it works though; there are just other, arguably more maintainable alternatives. One of them is a declarative code. The point is asking what you need, instead of how to get there.
In your particular case, this can look like the following. First, you need to find out what is it that you’re looking for, that is, discover abstractions. In your case, it looks like you need a date. Not just any date, but the one having some standard representation. Say, ISO8601 date. There are at least two implementations: the first one is a date parsed from an ISO8601-formatted string (or a string in any other format actually), and the second is some future date which is a day later. Thus, the whole code could look like that:
For more examples with datetime juggling check out this one.
adding 1 day to a DATETIME format value
In certain situations I want to add 1 day to the value of my DATETIME formatted variable:
What is the best way to do this?
9 Answers 9
There’s more then one way to do this with DateTime which was introduced in PHP 5.2. Unlike using strtotime() this will account for daylight savings time and leap year.
If you want to do this in PHP:
If you want to add the date in MySQL:
There are some valid values as examples :
So, in your case you can use the following.
If it’s only adding 1 day, then using strtotime again is probably overkill.
You can use as following.
You can also set days as constant and use like below.
I suggest start using Zend_Date classes from Zend Framework. I know, its a bit offtopic, but I’ll like this way 🙂
Using server request time to Add days. Working as expected.
Here ‘+2 days’ to add any number of days.
There is a more concise and intuitive way to add days to php date. Don’t get me wrong, those php expressions are great, but you always have to google how to treat them. I miss auto-completion facility for that.
Here is how I like to handle those cases:
For me, it’s way more intuitive and autocompletion works out of the box. No need to google for the solution each time.
As a nice bonus, you don’t have to worry about formatting the resulting value, it’s already is ISO8601 format.
This is meringue library, there are more examples here.
PHP: Add days to a date.
This is a short tutorial on how to add days to a given date using PHP. To do this, we can either use a combination of date and strtotime or we can take the OO approach and use the DateTime class.
Using the DateTime class to add days to a date.
Let’s start off by looking at a few examples using the DateTime class.
Adding 30 days to a date.
In the following example, I will add 30 days to a given date:
Add 7 days to a date using DateTime.
The PHP snippet above can be easily modified to add 7 days instead of 30. The only thing that needs changing is the line where we instantiated the DateInterval class:
Adding days to today’s date.
If you want to add days to today’s date, then you can simply omit the parameter in the constructor:
The DateTime object above will default to the current timestamp.
Other DateInterval examples.
Here are a few other interval specifications that can be used with the DateInterval class:
As of PHP version 7.1, you can even add microseconds onto a timestamp.
Using date and strtotime.
If you feel more comfortable using the date and strtotime functions, then you can use the following example:
In the code above, we added 30 days onto the current date.
However, if you are wanting to add days to a given date, then you will need to modify your approach a little:
As you can see, the strtotime function is actually pretty useful in the sense that you can almost write exactly what you want in plain English into the first parameter. For example, you can also tell it to add one month:
The DateTime class
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
Introduction
This class behaves the same as DateTimeImmutable except objects are modified itself when modification methods such as DateTime::modify() are called.
Class synopsis
Changelog
Table of Contents
User Contributed Notes 26 notes
Set Timezone and formatting.
= time ();
$timeZone = new \ DateTimeZone ( ‘Asia/Tokyo’ );
DateTime supports microseconds since 5.2.2. This is mentioned in the documentation for the date function, but bears repeating here. You can create a DateTime with fractional seconds and retrieve that value using the ‘u’ format string.
// Instantiate a DateTime with microseconds.
$d = new DateTime ( ‘2011-01-01T15:03:01.012345Z’ );
There is a subtle difference between the following two statments which causes JavaScript’s Date object on iPhones to fail.
/**
On my local machine this results in:
Both of these strings are valid ISO8601 datetime strings, but the latter is not accepted by the constructor of JavaScript’s date object on iPhone. (Possibly other browsers as well)
*/
?>
Our solution was to create the following constant on our DateHelper object.
class DateHelper
<
/**
* An ISO8601 format string for PHP’s date functions that’s compatible with JavaScript’s Date’s constructor method
* Example: 2013-04-12T16:40:00-04:00
*
* PHP’s ISO8601 constant doesn’t add the colon to the timezone offset which is required for iPhone
**/
const ISO8601 = ‘Y-m-d\TH:i:sP’ ;
>
?>
Small but powerful extension to DateTime
class Blar_DateTime extends DateTime <
= new Blar_DateTime ( ‘1879-03-14’ );
Albert Einstein would now be 130 years old.
Albert Einstein would now be 130 Years, 10 Months, 10 Days old.
Albert Einstein was on 2010-10-10 131 years old.
Example displaying each time format:
$dateTime = new DateTime();
The above example will output:
At PHP 7.1 the DateTime constructor incorporates microseconds when constructed from the current time. Make your comparisons carefully, since two DateTime objects constructed one after another are now more likely to have different values.
This caused some confusion with a blog I was working on and just wanted to make other people aware of this. If you use createFromFormat to turn a date into a timestamp it will include the current time. For example:
if you’d like to print all the built-in formats,
This might be unexpected behavior:
#or use the interval
#$date1->add(new DateInterval(«P1M»));
#will produce 2017-10-1
#not 2017-09-30
A good way I did to work with millisecond is transforming the time in milliseconds.
function timeToMilliseconds($time) <
$dateTime = new DateTime($time);
If you have timezone information in the time string you construct the DateTime object with, you cannot add an extra timezone in the constructor. It will ignore the timezone information in the time string:
$date = new DateTime(«2010-07-05T06:00:00Z», new DateTimeZone(«Europe/Amsterdam»));
will create a DateTime object set to «2010-07-05 06:00:00+0200» (+2 being the TZ offset for Europe/Amsterdam)
To get this done, you will need to set the timezone separately:
$date = new DateTime(«2010-07-05T06:00:00Z»);
$date->setTimeZone(new DateTimeZone(«Europe/Amsterdam»);
This will create a DateTime object set to «2010-07-05 08:00:00+0200»
It isn’t obvious from the above, but you can insert a letter of the alphabet directly into the date string by escaping it with a backslash in the format string. Note that if you are using «double» speech marks around the format string, you will have to further escape each backslash with another backslash! If you are using ‘single’ speech marks around the format string, then you only need one backslash.
For instance, to create a string like «Y2014M01D29T1633», you *could* use string concatenation like so:
please note that using
setTimezone
setTimestamp
setDate
setTime
etc..
$original = new DateTime(«now»);
so a datetime object is mutable
(Editors note: PHP 5.5 adds DateTimeImmutable which does not modify the original object, instead creating a new instance.)
Create function to convert GregorianDate to JulianDayCount
Note that the ISO8601 constant will not correctly parse all possible ISO8601 compliant formats, as it does not support fractional seconds. If you need to be strictly compliant to that standard you will have to write your own format.
Bug report #51950 has unfortunately be closed as «not a bug» even though it’s a clear violation of the ISO8601 standard.
It seems like, due to changes in the DateTimeZone class in PHP 5.5, when creating a date and specifying the timezone as a a string like ‘EDT’, then getting the timezone from the date object and trying to use that to set the timezone on a date object you will have problems but never know it. Take the following code:
Be aware that DateTime may ignore fractional seconds for some formats, but not when using the ISO 8601 time format, as documented by this bug:
$dateTime = DateTime::createFromFormat(
DateTime::ISO8601,
‘2009-04-16T12:07:23.596Z’
);
// bool(false)
Be aware of this behaviour:
In my opinion, the former date should be adjusted to 2014/11/30, that is, the last day in the previous month.
Here is easiest way to find the days difference between two dates:
If you’re stuck on a PHP 5.1 system (unfortunately one of my clients is on a rather horrible webhost who claims they cannot upgrade php) you can use this as a quick workaround:
If you need DateTime::createFromFormat functionality in versions class DateClass extends DateTime <
<>
$regexpArray [ ‘Y’ ] = «(?P 19|20\d\d)» ;
$regexpArray [ ‘m’ ] = «(?P 04|1[012])» ;
$regexpArray [ ‘d’ ] = «(?P 08|[12]3|3[01])» ;
$regexpArray [ ‘-‘ ] = «[-]» ;
$regexpArray [ ‘.’ ] = «[\. /.]» ;
$regexpArray [ ‘:’ ] = «[:]» ;
$regexpArray [ ‘space’ ] = «[\s]» ;
$regexpArray [ ‘H’ ] = «(?P 08|17|22)» ;
$regexpArray [ ‘i’ ] = «(?P32)» ;
$regexpArray [ ‘s’ ] = «(?P26)» ;