Adding three months to a date in PHP - php

I have a variable called $effectiveDate containing the date 2012-03-26.
I am trying to add three months to this date and have been unsuccessful at it.
Here is what I have tried:
$effectiveDate = strtotime("+3 months", strtotime($effectiveDate));
and
$effectiveDate = strtotime(date("Y-m-d", strtotime($effectiveDate)) . "+3 months");
What am I doing wrong? Neither piece of code worked.

Change it to this will give you the expected format:
$effectiveDate = date('Y-m-d', strtotime("+3 months", strtotime($effectiveDate)));

This answer is not exactly to this question. But I will add this since this question still searchable for how to add/deduct period from date.
$date = new DateTime('now');
$date->modify('+3 month'); // or you can use '-90 day' for deduct
$date = $date->format('Y-m-d h:i:s');
echo $date;

I assume by "didn't work" you mean that it's giving you a timestamp instead of the formatted date, because you were doing it correctly:
$effectiveDate = strtotime("+3 months", strtotime($effectiveDate)); // returns timestamp
echo date('Y-m-d',$effectiveDate); // formatted version

You need to convert the date into a readable value. You may use strftime() or date().
Try this:
$effectiveDate = strtotime("+3 months", strtotime($effectiveDate));
$effectiveDate = strftime ( '%Y-%m-%d' , $effectiveDate );
echo $effectiveDate;
This should work. I like using strftime better as it can be used for localization you might want to try it.

Tchoupi's answer can be made a tad less verbose by concatenating the argument for strtotime() as follows:
$effectiveDate = date('Y-m-d', strtotime($effectiveDate . "+3 months") );
(This relies on magic implementation details, but you can always go have a look at them if you're rightly mistrustful.)

The following should work,Please Try this:
$effectiveDate = strtotime("+1 months", strtotime(date("y-m-d")));
echo $time = date("y/m/d", $effectiveDate);

Following should work
$d = strtotime("+1 months",strtotime("2015-05-25"));
echo date("Y-m-d",$d); // This will print **2015-06-25**

Add nth Days, months and years
$n = 2;
for ($i = 0; $i <= $n; $i++){
$d = strtotime("$i days");
$x = strtotime("$i month");
$y = strtotime("$i year");
echo "Dates : ".$dates = date('d M Y', "+$d days");
echo "<br>";
echo "Months : ".$months = date('M Y', "+$x months");
echo '<br>';
echo "Years : ".$years = date('Y', "+$y years");
echo '<br>';
}

As of PHP 5.3, DateTime along with DateInterval could be a feasible option to achieve the desired result.
$months = 6;
$currentDate = new DateTime();
$newDate = $currentDate->add(new DateInterval('P'.$months.'M'));
echo $newDate->format('Y-m-d');
If you want to subtract time from a date, instead of add, use sub.
Here are more examples on how to use DateInterval:
$interval = new DateInterval('P1Y2M3DT4H5M6S');
// This creates an interval of 1 year, 2 months, 3 days, 4 hours, 5 minutes, and 6 seconds.
$interval = new DateInterval('P2W');
// This creates an interval of 2 weeks (which is equivalent to 14 days).
$interval = new DateInterval('PT1H30M');
// This creates an interval of 1 hour and 30 minutes (but no days or years, etc.).

The following should work, but you may need to change the format:
echo date('l F jS, Y (m-d-Y)', strtotime('+3 months', strtotime($DateToAdjust)));

public function getCurrentDate(){
return date("Y-m-d H:i:s");
}
public function getNextDateAfterMonth($date1,$monthNumber){
return date('Y-m-d H:i:s', strtotime("+".$monthNumber." months", strtotime($date1)));
}

Related

PHP date + 1 year is returning a date slightly less than 1 year [duplicate]

I'm trying to get a date that is one year from the date I specify.
My code looks like this:
$futureDate=date('Y-m-d', strtotime('+one year', $startDate));
It's returning the wrong date. Any ideas why?
$futureDate=date('Y-m-d', strtotime('+1 year'));
$futureDate is one year from now!
$futureDate=date('Y-m-d', strtotime('+1 year', strtotime($startDate)) );
$futureDate is one year from $startDate!
To add one year to todays date use the following:
$oneYearOn = date('Y-m-d',strtotime(date("Y-m-d", mktime()) . " + 365 day"));
For the other examples you must initialize $StartingDate with a timestamp value
for example:
$StartingDate = mktime(); // todays date as a timestamp
Try this
$newEndingDate = date("Y-m-d", strtotime(date("Y-m-d", strtotime($StaringDate)) . " + 365 day"));
or
$newEndingDate = date("Y-m-d", strtotime(date("Y-m-d", strtotime($StaringDate)) . " + 1 year"));
//1 year from today's date
echo date('d-m-Y', strtotime('+1 year'));
//1 year from from specific date
echo date('22-09-Y', strtotime('+1 year'));
hope this simpler bit of code helps someone in future :)
Try: $futureDate=date('Y-m-d',strtotime('+1 year',$startDate));
just had the same problem, however this was the simplest solution:
<?php (date('Y')+1).date('-m-d'); ?>
// Declare a variable for this year
$this_year = date("Y");
// Add 1 to the variable
$next_year = $this_year + 1;
$year_after = $this_year + 2;
// Check your code
echo "This year is ";
echo $this_year;
echo "<br />";
echo "Next year is ";
echo $next_year;
echo "<br />";
echo "The year after that is ";
echo $year_after;
I prefer the OO approach:
$date = new \DateTimeImmutable('today'); //'today' gives midnight, leave blank for current time.
$futureDate = $date->add(\DateInterval::createFromDateString('+1 Year'))
Use DateTimeImmutable otherwise you will modify the original date too!
more on DateTimeImmutable: http://php.net/manual/en/class.datetimeimmutable.php
If you just want from todays date then you can always do:
new \DateTimeImmutable('-1 Month');
If you are using PHP 5.3, it is because you need to set the default time zone:
date_default_timezone_set()
strtotime() is returning bool(false), because it can't parse the string '+one year' (it doesn't understand "one"). false is then being implicitly cast to the integer timestamp 0. It's a good idea to verify strtotime()'s output isn't bool(false) before you go shoving it in other functions.
From the docs:
Return Values
Returns a timestamp on success, FALSE
otherwise. Previous to PHP 5.1.0, this
function would return -1 on failure.
Try This
$nextyear = date("M d,Y",mktime(0, 0, 0, date("m",strtotime($startDate)), date("d",strtotime($startDate)), date("Y",strtotime($startDate))+1));
There is also a simpler and less sophisticated solution:
$monthDay = date('m/d');
$year = date('Y')+1;
$oneYearFuture = "".$monthDay."/".$year."";
echo"The date one year in the future is: ".$oneYearFuture."";
You can use strtotime() to get future time.
//strtotime('+1 day');
//strtotime('+1 week');
//strtotime('+1 month');
$now = date('Y-m-d');
$oneYearLaterFromNow = date('Y-m-d', strtotime('+1 year'));
$oneYearLaterFromAnyDate = date('Y-m-d', strtotime('+1 year', strtotime($anyValidDateString)));
In my case (i want to add 3 years to current date) the solution was:
$future_date = date('Y-m-d', strtotime("now + 3 years"));
To Gardenee, Treby and Daniel Lima:
what will happen with 29th February? Sometimes February has only 28 days :)
My solution is: date('Y-m-d', time()-60*60*24*365);
You can make it more "readable" with defines:
define('ONE_SECOND', 1);
define('ONE_MINUTE', 60 * ONE_SECOND);
define('ONE_HOUR', 60 * ONE_MINUTE);
define('ONE_DAY', 24 * ONE_HOUR);
define('ONE_YEAR', 365 * ONE_DAY);
date('Y-m-d', time()-ONE_YEAR);

How to get the current date in PHP, and add 1 month to the current date?

I'm coding a script where I require to save the current date, and the date 1 month from that date. I am pretty sure that the time() variable works, but I am not sure how to +1 month onto that?
Any ideas, suggestions. Cheers!
Try this
$today = date("Y-m-d");
$date = date('Y-m-d', strtotime('+1 month', $today));
or use DateTime()
$dt1 = new DateTime();
$today = $dt1->format("Y-m-d");
$dt2 = new DateTime("+1 month");
$date = $dt2->format("Y-m-d");
$time = strtotime("2010-12-11");
$final = date("Y-m-d", strtotime("+1 month", $time));
(OR)
strtotime( "+1 month", strtotime( $time ) );
this returns a timestamp that can be used with the date function
Use this:
Current Date:
echo "Today is " . date("Y/m/d");
1 Month to the Current Date:
$time = strtotime(date("Y/m/d"));
$final = date("Y-m-d", strtotime("+1 month", $time));
<?php
$current_time = date("Y-M-d h:i:s",time()); // Getting Current Date & Time
print $current_time; // Current Date & Time Printing for display purpose
$future_timestamp = strtotime("+1 month"); // Getting timestamp of 1 month from now
$final_future = date("Y-M-d h:i:s",+$future_timestamp); // Getting Future Date & Time of 1 month from now
print $final_future; // Printing Future time for display purpose
?>
shorter : $today=date("Y-m-d"); $date=
This one liner worked for me:
$monthFromToday = date("Y-m-d", strtotime("+1 month", strtotime(date("Y/m/d"))));
The given answers may not give you the results you might expect or desire.
Consider:
$today = "29Jan2018";
$nextMonth = date('dMY', strtotime('+1 month', (strtotime($today))));
echo $today // yields 29Jan2018
echo $nextMonth // yields 01Mar2018
$today = date("Y-m-d");
$enddate = date('Y-m-01',strtotime($today. ' + 1 months'));
You could also consider using the Carbon package.
The solution would look like this:
use Carbon\Carbon
$now = Carbon::now;
$now->addMonth();
Here is the link for reference https://carbon.nesbot.com/docs/

Php: Add variable amount days to Y-m-d date format

i'm trying to add days to a date with the 'Y-m-d' format:
$oldDate = '2013-05-15';
$newDate = date('Y-m-d', strtotime($oldDate. " + 5 days"));
This ouputs '2013-5-20', but below:
$oldDate = '2013-05-15';
$addedDays = 5;
$newDate = date('Y-m-d', strtotime($oldDate. " + $addedDays days"));
doesn't work, it only outputs '1970-01-01', which doesn't make sense because i only tried to put the days to be added in a variable. They're basically the same code. I appreciate the help trying to understand this. Thanks!
However the code is right and works, just in case try
$newDate = date('Y-m-d', strtotime($oldDate. " + {$addedDays} days"));
Use the DateTime class. It will spare you a lot of head-ache.
// Create a DateTime object
$date = new DateTime('2013-05-15');
// Original date
echo $date->format('d. F Y'), '<br>';
// Add 5 days
$date->modify('+5 days');
// Modified date
echo $date->format('d. F Y'), '<br>';
I had checked it, but it doesn't work on my computer (likely due to the PHP version). I found an alternative solution, though:
$timeBase = time();
$sDays2change = '+182'; // 6 months
$newtime = strtotime($sDays2change . ' day', $timeBase);
echo date('d/m/Y', $newtime);

PHP: Incorrect strtotime()

I had gone through various stackoverflow solutions and other blogs but still it doesn't fix my problem.
Let's say that the date today is: 2013-12-28 and I want to get the date after 1 month and it is supposed to display 2014-01-28.
$date = date('o-m-d');
$final = date('o-m-d', strtotime("+1 month", $date));
echo $final;
Above is my code. It returns 02/01/1970.
I have also tried the mktime method but still it displays the 1970 output.
What am I doing wrong?
BTW. I am working this on a hosted server.
Thanks ahead. :)
Use DateTime function modify
$date = new DateTime( 'o-m-d' );
echo $date->modify( '+1 month' )->format('o-m-d');
If you want the current date +1 month use:
$final = date('o-m-d', strtotime("+1 month"));
Or with a given date:
$date = date('o-m-d');
$final = date('o-m-d', strtotime($date . " +1 month"));
echo $final;
If you want to use the second parameter of strtotime it has to be a timestamp.
Go the OOP way..
<?php
$date = new DateTime('2013-12-28');
$date->add(new DateInterval('P1M'));
echo $date->format('Y-m-d'); //prints 2014-01-28

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);

Categories