Adding two weeks php - php

I'm trying to add two weeks to sql result that comes back as 16/11/2016. When I do something like
$twoweeks = strtotime($time_db);
$expiry_date = $twoweeks;
$date = strtotime($expiry_date);
$date = strtotime("+14 day", $date);
echo date('d/m/y', $date);
I keeping getting 15/01/70... any ideas?

You made a mistake on line 4 by putting a number variable as a first parameter of strtotime. strtotime expects a string of a valid date/time format as a first parameter otherwise it returns FALSE.
How I think your code should be:
$twoweeks = strtotime($time_db);
$date = strtotime("+ 2 weeks", $twoweeks);
echo date('d/m/y', $date);
Or maybe even:
echo date('d/m/y', strtotime($time_db . ' + 2 weeks'));

You can use
$numberOfWeeks = 2;
$newTime = strtotime($time_db) + ($numberOfWeeks * 60 * 60 * 24 * 7);
or you can do directly in (mysql) select
select date_add( your_column, INTERVAL 2 WEEK) from my_table;

What's happening here is that your 16/11/2016 is day-month-year and the slashes are an issue.
Had your date been 11/16/2016, you would have found that it would have been OK.
You need to convert/replace those to dashes/hyphens.
$time_db = "16/11/2016";
$time_db = str_replace('/', '-', $time_db);
$two_weeks_later = date('d-m-Y',strtotime($time_db . "+14 days"));
// or display as Year-month-day
// $two_weeks_later = date('Y-m-d',strtotime($time_db . "+14 days"));
echo $two_weeks_later;
When working with dates (and times), it's best to use the built-in MySQL date/time functions, rather than storing them as plain text; it's a lot less trouble and much easier when querying.
Reference:
http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html

$date = date('Y-m-d H:i:s',time());
$date = strtotime($date);
$date = strtotime("+14 day", $date);
$valuedate= date('Y-m-d H:i:s',$date);
Try this

Related

Get 30 days back date along with time

I want to calculate EXACT past 30 days time period in php from now (for example 30 aug 14 23:06) to 30 days back (for example 1 aug 14 23:06). I wrote this where current datetime goes in $d1 and past 30 days datetime goes in $d2 but somehow i am not getting correct results. Any idea?
$url=$row["url"];
$pageid=getPageID($url);
$date=date('y-m-d g:i');
$d1=strtotime($date);
$d2=date(strtotime('today - 30 days'));
Thanks
The problem is likely caused by the malformed date() call. The first argument passed to date() should be the format (as shown in the Docs) and the second should be an optional timestamp.
Try this:
$d2 = date('c', strtotime('-30 days'));
PHPFiddle
As a short aside, the whole snippet can be simplified as follows:
$url = $row["url"];
$pageid = getPageID($url);
$date = date('y-m-d g:i');
$d1 = time();
$d2 = date('y-m-d g:i', strtotime('-30 days'));
You can also use the DateTime class's sub() method together with an DateInterval:
$now = new DateTime();
$back = $now->sub(DateInterval::createFromDateString('30 days'));
echo $back->format('y-m-d g:i');
if you would like to get out put as 2014-08-01 then try the below code. thanks
$date = '2014-08-30 23:06';
$new_date = date('Y-m-d G:i', strtotime($date.' - 29 days'));
echo "30 days back is " . $new_date;
From your brief description and example given, I believe that you want the date to be 30 days back and time to be the same as of now. The below code will serve this purpose. Thanks.
<?php
$date=date('y-m-d g:i');
$time=date('g:i');
echo "Todays date:" . $date. "<br>";
$d2 = date('y-m-d', strtotime('-30 days'));
echo "30 days back:" . $d2 . ' ' .$time;
?>
Try:
echo date("Y-m-d h:i:s",strtotime('-30 days'));
For more detail click here
Very simple two lines of code
$date = new DateTime();
echo $date->modify('-30 day')->format('y-m-d g:i');
I know you said with PHP, however, I can't imagine not getting the records from a DB. If you want to do so from the DB,use:
$sql='SELECT * FROM myTable WHERE date > CURRENT_DATE - INTERVAL 30 DAY';
$pdo->query($sql);
Very simple one lines of code:
echo (new DateTime())->modify('-30 day')->format('y-m-d g:i');
In the example below, it makes no sense if the variable $date is not
used anywhere else!
$date = new DateTime();
echo $date->modify('-30 day')->format('y-m-d g:i');
Sample answer is
$dateBack30Days=date('Y-m-d g:i', strtotime('-30 days'));

Adding three months to a date in 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)));
}

How to increment date with 1 (day/year) in PHP?

I have a date stored in an array:
$this->lines['uDate']
The format of the date is not fixed. I can be changed with this:
define('DATETIME_FORMAT', 'y-m-d H:i');
How can I increment my uDate with a certain number of days or years?
My question is related to this one:
increment date by one month
However, in my case the date format in dynamic.
So, can I do this?
$time= $this->lines['uDate'];
$time = date(DATETIME_FORMAT, strtotime("+1 day", $time));
$this->lines['uDate']= $time;
date_add()
and consider changes like:
define(DATETIME_FORMAT, 'y-m-d H:i');
$time = date(DATETIME_FORMAT, strtotime("+1 day", $time));
You can use some simple calculation to do it if you have the timestamp.
$date = strtotime($this->lines['uDate']); //assuming it's not a timestamp\
$date = $date + (60 * 60 * 24); //increase date by 1 day
echo date('d-m-y', $date);
$date = $date + (60 * 60 * 24 * 365); //increase date by a year
echo date('d-m-y', $date);
You can also use the mktime() method to do this : http://php.net/manual/en/function.mktime.php
function add_date($givendate,$day=0,$mth=0,$yr=0)
{
$cd = strtotime($givendate);
$newdate = date('Y-m-d h:i:s', mktime(date('h',$cd),
date('i',$cd), date('s',$cd), date('m',$cd)+$mth,
date('d',$cd)+$day, date('Y',$cd)+$yr));
return $newdate;
}
I have found this in PHP help
another useful way, if you want an object rather than a string:
$date = DateTimeImmutable::createFromFormat('Y-m-d', '2022-01-05'); // just an exemplary date
$date = $date->add(date_interval_create_from_date_string('1 day')); // count up
notable difference:
date_add() changes the original object, while DateTimeImmutable::add() does not and simply returns the new object. Depending on the desired behavior, use one or the other.

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

Date minus 1 year?

I've got a date in this format:
2009-01-01
How do I return the same date but 1 year earlier?
You can use strtotime:
$date = strtotime('2010-01-01 -1 year');
The strtotime function returns a unix timestamp, to get a formatted string you can use date:
echo date('Y-m-d', $date); // echoes '2009-01-01'
Use strtotime() function:
$time = strtotime("-1 year", time());
$date = date("Y-m-d", $time);
Using the DateTime object...
$time = new DateTime('2099-01-01');
$newtime = $time->modify('-1 year')->format('Y-m-d');
Or using now for today
$time = new DateTime('now');
$newtime = $time->modify('-1 year')->format('Y-m-d');
an easiest way which i used and worked well
date('Y-m-d', strtotime('-1 year'));
this worked perfect.. hope this will help someone else too.. :)
On my website, to check if registering people is 18 years old, I simply used the following :
$legalAge = date('Y-m-d', strtotime('-18 year'));
After, only compare the the two dates.
Hope it could help someone.
// set your date here
$mydate = "2009-01-01";
/* strtotime accepts two parameters.
The first parameter tells what it should compute.
The second parameter defines what source date it should use. */
$lastyear = strtotime("-1 year", strtotime($mydate));
// format and display the computed date
echo date("Y-m-d", $lastyear);
Although there are many acceptable answers in response to this question, I don't see any examples of the sub method using the \Datetime object: https://www.php.net/manual/en/datetime.sub.php
So, for reference, you can also use a \DateInterval to modify a \Datetime object:
$date = new \DateTime('2009-01-01');
$date->sub(new \DateInterval('P1Y'));
echo $date->format('Y-m-d');
Which returns:
2008-01-01
For more information about \DateInterval, refer to the documentation: https://www.php.net/manual/en/class.dateinterval.php
You can use the following function to subtract 1 or any years from a date.
function yearstodate($years) {
$now = date("Y-m-d");
$now = explode('-', $now);
$year = $now[0];
$month = $now[1];
$day = $now[2];
$converted_year = $year - $years;
echo $now = $converted_year."-".$month."-".$day;
}
$number_to_subtract = "1";
echo yearstodate($number_to_subtract);
And looking at above examples you can also use the following
$user_age_min = "-"."1";
echo date('Y-m-d', strtotime($user_age_min.'year'));

Categories