PHP datetime add 6 months and 1 year - php

I have a date set using PHP datetime like this..
$originaldate = 2019-01-10 17:52:17
$converted = DateTime::createFromFormat("Y-m-d H:i:s", $originaldate);
The date is successfuly converted into a PHP DateTime object, now I am trying to add create 2 new dates that are 6 months and 1 year ahead of this date.
Whats the best way to achieve this?

You should look into php class DateInterval http://php.net/manual/en/class.dateinterval.php
Here's an example:
$converted = DateTime::createFromFormat("Y-m-d H:i:s", $originaldate);
$converted1Year = $converted->add(new DateInterval("P1Y"));//add one year //object reference is the same so adding a year altered original object and a reference to it is passed back, not copied
$converted2 = DateTime::createFromFormat("Y-m-d H:i:s", $originaldate);
$converted6months = $converted2->add(new DateInterval("P6M")); // add 6 months
And as suggested in the comments here's the DateTimeImmutable equivalent:
$converted = DateTimeImmutable::createFromFormat("Y-m-d H:i:s", $originaldate);
$converted1Year = $converted->add(new DateInterval("P1Y"));
$converted6Months = $converted->add(new DateInterval("P6M"));

Check out DateTime::add
$converted->add(new DateInterval("P18M")); // add 18 months
P18M means 18 month interval

You can clone the time to create a duplicate and use DateTime::modify to change the new date.
Try this;
$sixMonths = clone $converted;
$sixMonths->modify('+6 months');
$oneYear = clone $converted;
$oneYear->modify('+1 year');

$converted = $converted->modify('+6 months');
$converted = $converted->modify('+1 year');

Like so:
$sixMonths = date('Y-m-d', strtotime($converted. ' + 6 months'));
$oneYear = date('Y-m-d', strtotime($converted. ' + 1 year'));

The format already default ("Y-m-d H:i:s"). You don't need to use CreateFromFormat, unless you are handle data from 3rd party. My suggestion for the code would be like this
$originaldate = '2019-01-10 17:52:17';
$converted = new DateTime( $originaldate ); //prefer like this
//DateTime::createFromFormat("Y-m-d H:i:s", $originaldate); //after browsing this is recomended
$date6Month = new DateTime( $originaldate );
$date1Year = new DateTime( $originaldate );
$dateBack = new DateTime( $originaldate );
//$date6Month = $date1Year = $dateBack= $converted;
//prefer to use different variable for every date. Not copy
echo "ori:".$converted ->format('Y-m-d H:i:s') . "\n";
//ori:2019-01-10 17:52:17
##6 month later
$date6Month ->add(new DateInterval('P6M'));
echo "6 month:".$date6Month ->format('Y-m-d H:i:s') . "\n";
//6 month:2019-07-10 17:52:17
##1 year later
$date1Year ->add(new DateInterval('P1Y'));
echo "1 year:".$date1Year ->format('Y-m-d H:i:s') . "\n";
//1 year:2020-01-10 17:52:17
//1 year:2020-07-10 17:52:17 (wrong if using copy main parameter)
$date1Year ->add( DateInterval::createFromDateString('1 Years') );
echo "1 year (later):".$date1Year ->format('Y-m-d H:i:s') . "\n";
//1 year (later):2021-01-10 17:52:17
//1 year (later):2021-07-10 17:52:17 (wrong if using copy main parameter)
you can use DateInterval::createFromDateString for readable code than using format. My suggestion is to separated the variable not copy from the origin.
The format you can use on DateInterval
Start "P" when contain Day, Month and Year
Format
Info
Example
Y
Year
1Y
M
Month
3M
D
Day
5D
example: P1Y3M5D
Always Start "P" before "T" if not contain Day, Month and Year (PT1H). If not start it with "T"
Format
Info
Example
H
HOUR
1H
M
MINUTES
3M
S
SECONDS
5S
F
MICROSECOND (php7+)
5F
example: PT1H3M5S
wrong: T1H3M5S
other example (from link below)
date_default_timezone_set('America/Phoenix');
//is important to add when your time are detail
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P7Y5M4DT4H3M2S'));
echo $date->format('Y-m-d H:i:s') . "\n";
//2007-06-05 04:03:02
$originaldate = 2019-01-10 17:52:17
$dateBack = $dateBack2 = new DateTime( $originaldate );
//if you want to substract the value you can use this
$dateBack ->sub(new DateInterval('P1Y2M3DT1H4M1S'));
echo $dateBack ->format('Y-m-d H:i:s') . "\n";
//output: 2019-05-07 16:48:16
$dateBack2=$converted;
$formatDay='P1Y3M6D'; //only year, month and day
$formatTime='T1H3M6S'; //only hour, minutes and seconds
$dateBack2 ->sub(new DateInterval( $formatDay.$formatTime ));
echo $dateBack ->format('Y-m-d H:i:s') . "\n";
//2018-02-01 15:45:10
as mention on the phpmanual, there is other format (microtime) that's not include on this example.
related link
Date Time PHP
Date Interval
Format on Interval
Date Interval create using String

Related

Decrease month by one in strtotime?

all
Decrease month by one in strtotime in this loop.
$twitter_val7 .='{
date: new Date('.date("Y",strtotime($date)).', '.date("m",strtotime($date)).', '.date("d",strtotime($date)).'),
value: '.$result_twitter->counts.'
},';
To decrease by 1 month using strtotime() you literally tell it to decrease by one month:
strtotime($date . ' - 1 month');
Assuming, of course, that $date is a format strtotime() understands.
I would do it like this .. i guess $date would go in place of '2000-01-01':
$initial = new DateTime('2000-01-01');
$interval = new DateInterval('P1M');
$newdate = $initial->sub( $interval );
echo $newdate->format('Y-m-d H:i:s');
To decrease month by using strtotime
$date='2014-09-03';
$numMonth=1;//here you can pass no. of month
$resultDate=date('Y-m-d',strtotime($date . " - $numMonth month"));

Adding minutes to date time in PHP

I'm really stuck with adding X minutes to a datetime, after doing lots of google'ing and PHP manual reading, I don't seem to be getting anywhere.
The date time format I have is:
2011-11-17 05:05: year-month-day hour:minute
Minutes to add will just be a number between 0 and 59
I would like the output to be the same as the input format with the minutes added.
Could someone give me a working code example, as my attempts don't seem to be getting me anywhere?
$minutes_to_add = 5;
$time = new DateTime('2011-11-17 05:05');
$time->add(new DateInterval('PT' . $minutes_to_add . 'M'));
$stamp = $time->format('Y-m-d H:i');
The ISO 8601 standard for duration is a string in the form of P{y}Y{m1}M{d}DT{h}H{m2}M{s}S where the {*} parts are replaced by a number value indicating how long the duration is.
For example, P1Y2DT5S means 1 year, 2 days, and 5 seconds.
In the example above, we are providing PT5M (or 5 minutes) to the DateInterval constructor.
PHP's DateTime class has a useful modify method which takes in easy-to-understand text.
$dateTime = new DateTime('2011-11-17 05:05');
$dateTime->modify('+5 minutes');
You could also use string interpolation or concatenation to parameterize it:
$dateTime = new DateTime('2011-11-17 05:05');
$minutesToAdd = 5;
$dateTime->modify("+{$minutesToAdd} minutes");
$newtimestamp = strtotime('2011-11-17 05:05 + 16 minute');
echo date('Y-m-d H:i:s', $newtimestamp);
result is
2011-11-17 05:21:00
Live demo is here
If you are no familiar with strtotime yet, you better head to php.net to discover it's great power :-)
You can do this with native functions easily:
strtotime('+59 minutes', strtotime('2011-11-17 05:05'));
I'd recommend the DateTime class method though, just posted by Tim.
I don't know why the approach set as solution didn't work for me.
So I'm posting here what worked for me in hope it can help anybody:
$startTime = date("Y-m-d H:i:s");
//display the starting time
echo '> '.$startTime . "<br>";
//adding 2 minutes
$convertedTime = date('Y-m-d H:i:s', strtotime('+2 minutes', strtotime($startTime)));
//display the converted time
echo '> '.$convertedTime;
I thought this would help some when dealing with time zones too. My modified solution is based off of #Tim Cooper's solution, the correct answer above.
$minutes_to_add = 10;
$time = new DateTime();
**$time->setTimezone(new DateTimeZone('America/Toronto'));**
$time->add(new DateInterval('PT' . $minutes_to_add . 'M'));
$timestamp = $time->format("Y/m/d G:i:s");
The bold line, line 3, is the addition. I hope this helps some folks as well.
A bit of a late answer, but the method I would use is:
// Create a new \DateTime instance
$date = DateTime::createFromFormat('Y-m-d H:i:s', '2015-10-26 10:00:00');
// Modify the date
$date->modify('+5 minutes');
// Output
echo $date->format('Y-m-d H:i:s');
Or in PHP >= 5.4
echo (DateTime::createFromFormat('Y-m-d H:i:s', '2015-10-26 10:00:00'))->modify('+5 minutes')->format('Y-m-d H:i:s')
If you want to give a variable that contains the minutes.
Then I think this is a great way to achieve this.
$minutes = 10;
$maxAge = new DateTime('2011-11-17 05:05');
$maxAge->modify("+{$minutes} minutes");
Use strtotime("+5 minute", $date);
Example:
$date = "2017-06-16 08:40:00";
$date = strtotime($date);
$date = strtotime("+5 minute", $date);
echo date('Y-m-d H:i:s', $date);
As noted by Brad and Nemoden in their answers above, strtotime() is a great function. Personally, I found the standard DateTime Object to be overly complicated for many use cases. I just wanted to add 5 minutes to the current time, for example.
I wrote a function that returns a date as a string with some optional parameters:
1.) time:String | ex: "+5 minutes" (default = current time)
2.) format:String | ex: "Y-m-d H:i:s" (default = "Y-m-d H:i:s O")
Obviously, this is not a fully featured method. Just a quick and simple function for modifying/formatting the current date.
function get_date($time=null, $format='Y-m-d H:i:s O')
{
if(empty($time))return date($format);
return date($format, strtotime($time));
}
// Example #1: Return current date in default format
$date = get_date();
// Example #2: Add 5 minutes to the current date
$date = get_date("+5 minutes");
// Example #3: Subtract 30 days from the current date & format as 'Y-m-d H:i:s'
$date = get_date("-30 days", "Y-m-d H:i:s");
one line mysql datetime format
$mysql_date_time = (new DateTime())->modify('+15 minutes')->format("Y-m-d H:i:s");
One more example of a function to do this: (changing the time and interval formats however you like them according to this for function.date, and this for DateInterval):
(I've also written an alternate form of the below function.)
// Return adjusted time.
function addMinutesToTime( $dateTime, $plusMinutes ) {
$dateTime = DateTime::createFromFormat( 'Y-m-d H:i', $dateTime );
$dateTime->add( new DateInterval( 'PT' . ( (integer) $plusMinutes ) . 'M' ) );
$newTime = $dateTime->format( 'Y-m-d H:i' );
return $newTime;
}
$adjustedTime = addMinutesToTime( '2011-11-17 05:05', 59 );
echo '<h1>Adjusted Time: ' . $adjustedTime . '</h1>' . PHP_EOL . PHP_EOL;
Without using a variable:
$yourDate->modify("15 minutes");
echo $yourDate->format( "Y-m-d H:i");
With using a variable:
$interval= 15;
$yourDate->modify("+{$interval } minutes");
echo $yourDate->format( "Y-m-d H:i");

PHP: add seconds to a date

I have $adate; which contains:
Tue Jan 4 07:59:59 2011
I want to add to this date the following:
$duration=674165; // in seconds
Once the seconds are added I need the result back into date format.
I don't know what I'm doing, but I am getting odd results.
Note: both variables are dynamic. Now they are equal to the values given, but next query they will have different values.
If you are using php 5.3+ you can use a new way to do it.
<?php
$date = new DateTime();
echo $date->getTimestamp(). "<br>";
$date->add(new DateInterval('PT674165S')); // adds 674165 secs
echo $date->getTimestamp();
?>
Just use some nice PHP date/time functions:
$adate="Tue Jan 4 07:59:59 2011";
$duration=674165;
$dateinsec=strtotime($adate);
$newdate=$dateinsec+$duration;
echo date('D M H:i:s Y',$newdate);
Given the fact that $adate is a timestamp (if that's the case), you could do something like this:
$duration = 674165;
$result_date = strtotime(sprintf('+%d seconds', $duration), $adate);
echo date('Y-m-d H:i:s', $result_date);
// add 20 sec to now
$duration = 20;
echo date("Y-m-d H:i:s", strtotime("+$duration sec"));
Do this:
$seconds = 1;
$date_now = "2016-06-02 00:00:00";
echo date("Y-m-d H:i:s", (strtotime(date($date_now)) + $seconds));
$current_time_zone = 150;
date("Y-m-d H:i:s",strtotime(date("Y-m-d H:i:s"))+$current_time_zone);
I made this example for a timezone, but if you change some parts it may help you out:
$seconds_to_add = 30;
$time = new DateTime();
$time->setTimezone(new DateTimeZone('Europe/London'));
$time2 = $time->format("Y/m/d G:i:s");
$time->add(new DateInterval('PT' . $seconds_to_add . 'S'));
$timestamp = $time->format("Y/m/d G:i:s");
echo $timestamp;
echo '========';
echo $time2;
Result:
2018/06/17 3:16:23========2018/06/17 3:15:53
It would be easier with DateTime::modify
(new DateTime($str))->modify("+$duration seconds"); //$str is the date in string
I have trouble with strtotime() to resolve my problem of add dynamic data/time value in the current time
This was my solution:
$expires = 3600; //my dynamic time variable (static representation here)
$date = date_create(date('Y-m-d H:i:s')); //create a date/time variable (with the specified format - create your format, see (1))
echo date_format($date, 'Y-m-d H:i:s')."<br/>"; //shows the date/time variable without add seconds/time
date_add($date, date_interval_create_from_date_string($expires.' seconds')); //add dynamic quantity of seconds to data/time variable
echo date_format($date, 'Y-m-d H:i:s'); //shows the new data/time value
font: https://secure.php.net/manual/en/datetime.add.php (consult Object Oriented style too, the Elzo Valugi solution)
(1) https://secure.php.net/manual/en/function.date.php

Adding days to $Date in PHP

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?
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
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"
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)
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";
You can also use the following format
strtotime("-3 days", time());
strtotime("+1 day", strtotime($date));
You can stack changes this way:
strtotime("+1 day", strtotime("+1 year", strtotime($date)));
Note the difference between this approach and the one in other answers: instead of concatenating the values +1 day and <timestamp>, you can just pass in the timestamp as the second parameter of strtotime.
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
Using a variable for Number of days
$myDate = "2014-01-16";
$nDays = 16;
$newDate = strtotime($myDate . '+ '.$nDays.' days');
echo new Date('d/m/Y', $newDate); //format new date
Here is the simplest solution to your query
$date=date_create("2013-03-15"); // or your date string
date_add($date,date_interval_create_from_date_string("40 days"));// add number of days
echo date_format($date,"Y-m-d"); //set date format of the result
This works. You can use it for days, months, seconds and reformat the date as you require
public function reformatDate($date, $difference_str, $return_format)
{
return date($return_format, strtotime($date. ' ' . $difference_str));
}
Examples
echo $this->reformatDate('2021-10-8', '+ 15 minutes', 'Y-m-d H:i:s');
echo $this->reformatDate('2021-10-8', '+ 1 hour', 'Y-m-d H:i:s');
echo $this->reformatDate('2021-10-8', '+ 1 day', 'Y-m-d H:i:s');
To add a certain number of days to a date, use the following function.
function add_days_to_date($date1,$number_of_days){
/*
//$date1 is a string representing a date such as '2021-04-17 14:34:05'
//$date1 =date('Y-m-d H:i:s');
// function date without a secrod argument returns the current datetime as a string in the specified format
*/
$str =' + '. $number_of_days. ' days';
$date2= date('Y-m-d H:i:s', strtotime($date1. $str));
return $date2; //$date2 is a string
}//[end function]
All have to use bellow code:
$nday = time() + ( 24 * 60 * 60);
echo 'Now: '. date('Y-m-d') ."\n";
echo 'Next Day: '. date('Y-m-d', $nday) ."\n";
Another option is to convert your date string into a timestamp and then add the appropriate number of seconds to it.
$datetime_string = '2022-05-12 12:56:45';
$days_to_add = 1;
$new_timestamp = strtotime($datetime_string) + ($days_to_add * 60 * 60 * 24);
After which, you can use one of PHP's various date functions to turn the timestamp into a date object or format it into a human-readable string.
$new_datetime_string = date('Y-m-d H:i:s', $new_timestamp);

Time calculation in php (add 10 hours)?

I get the time:
$today = time();
$date = date('h:i:s A', strtotime($today));
if the current time is "1:00:00 am", how do i add 10 more hours to become 11:00:00 am??
strtotime() gives you a number back that represents a time in seconds. To increment it, add the corresponding number of seconds you want to add. 10 hours = 60*60*10 = 36000, so...
$date = date('h:i:s A', strtotime($today)+36000); // $today is today date
Edit: I had assumed you had a string time in $today - if you're just using the current time, even simpler:
$date = date('h:i:s A', time()+36000); // time() returns a time in seconds already
$tz = new DateTimeZone('Europe/London');
$date = new DateTime($today, $tz);
$date->modify('+10 hours');
// use $date->format() to outputs the result.
see DateTime Class
(PHP 5 >= 5.2.0)
You can simply make use of the DateTime class , OOP Style.
<?php
$date = new DateTime('1:00:00');
$date->add(new DateInterval('PT10H'));
echo $date->format('H:i:s a'); //"prints" 11:00:00 a.m
$date = date('h:i:s A', strtotime($today . ' + 10 hours'));
(untested)
$date = date('h:i:s A', strtotime($today . " +10 hours"));
Full code that shows now and 10 minutes added.....
$nowtime = date("Y-m-d H:i:s");
echo $nowtime;
$date = date('Y-m-d H:i:s', strtotime($nowtime . ' + 10 minute'));
echo "<br>".$date;
In order to increase or decrease time using strtotime you could use a Relative format in the first argument.
In your case to increase the current time by 10 hours:
$date = date('h:i:s A', strtotime('+10 hours'));
In case you need to apply the change to another timestamp, the second argument can be specified.
Note:
Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2.
So, the recommended way since PHP 5.3:
$dt = new DateTime(); // assuming we need to add to the current time
$dt->add(new DateInterval('PT10H'));
$date = $dt->format('h:i:s A');
or using aliases:
$dt = date_create(); // assuming we need to add to the current time
date_add($dt, date_interval_create_from_date_string('10 hours'));
$date = date_format($dt, 'h:i:s A');
In all cases the default time zone will be used unless a time zone is specified.

Categories