This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
increment date by one month
I have the following code to sum dates:
$var1 = date("d/m/Y");
$dia = substr($var1,0,2);
$mes = substr($var1,3,2);
$a_o = substr($var1,6,4);
$date = $a_o."-".$mes."-".$dia;
$new_date = strtotime( "+3 month", strtotime($date));
$new_date = date('d/m/Y', $new_date);
echo $new_date;
That is the normal method I found on php.net but when I tried to change $var1 with another date, for example, '21/07/2020' the result is '31/01/1970', I don't know what's wrong. I tried many forms but the result is the same.
How can I fix this? Or what other forms exist to add X months to a date?
Look into the date_add() function that was added for 5.3.0.
DateTime::add -- date_add — Adds an amount of days, months, years,
hours, minutes and seconds to a DateTime object
<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P10D'));
echo $date->format('Y-m-d') . "\n";
?>
There is also the date_modify() function that was added for 5.2.0.
DateTime::modify -- date_modify — Alters the timestamp
<?php
$date = new DateTime('2006-12-12');
$date->modify('+1 day');
echo $date->format('Y-m-d');
?>
You're going about it completely wrong. date() gives you a nicely formatted STRING. If you want to do math with dates, you need to work with the native PHP date/time values, which are simple integers - unix time stamps.
You're taking that unix timestamp (the default value in date()), converting it to a string, taking apart that string, recombining the string in a different order, then converting it back to a timestamp, then converting the timestamp into a different formatted string. That's like going on a 500mile road trip so you can cross the street.
Any reason you can't simply do:
$new_date = date('d/m/Y', strtotime('+3 month'));
and eliminate everything else in your code snippet?
In your place, I'll trasform the date in timestamp, then I'll add the new date in seconds (i.e. 3 months are 60 * 60 * 24 * 90 = 7 776 000 secs.) and then transform back in date :P
Related
This question already has answers here:
Using strtotime for dates before 1970
(7 answers)
Closed 4 years ago.
date('m/d/Y', strtotime('7-Jan-69'))
It gives output as 01/07/2069, Where
date('m/d/Y', strtotime('7-Jan-75'))
This gives output as 01/07/1975, Why is so and what is the catch?
From the docs:
The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC)
Any date before 1970 will be understand as date after 1970
do you need something like this?
<?
// function to convert string and print
function convertString ($date)
{
// convert date and time to seconds
$sec = strtotime($date);
// convert seconds into a specific format
$date = date("Y-m-d H:i", $sec);
// append seconds to the date and time
$date = $date . ":00";
// print final date and time
echo $date;
}
// Driver code
$date = "06/12/2014 04:13 PM";
convertString($date);
?>
To fix that you can use DateTime instead of strtotime() like below,
<?php
$date = $dt = new DateTime('7-Jan-75');
echo $date->format('m/d/Y');
?>
Reason for not working in your case with strtotime:
If the number of the year is specified in a two digit format, the values between 00-69 are mapped to 2000-2069 and 70-99 to 1970-1999.
See the notes below for possible differences on 32bit systems
(possible dates might end on 2038-01-19 03:14:07).
DEMO: https://3v4l.org/d8eoK
I am working on generating recurring dates using PHP to process the dates. I have a $startDateTime and $endDateTime. These two variables are for the first date in the series.
If the even repeats every Tuesday I need something along the lines of
$repeatDay = "Tuesday";
$followingDay = strtotime($startDateTime. " following $repeatDay");
Using "next $repeatDay" doesn't work since I am not generating the date from todays date.
EDIT:
It seems that every five loops the time jumps forward an hour in the date. This may be because $start="2014-04-29 11:00:00" and strtotime is only converting the date correctly.
How should I convert 2014-04-29 11:00:00 to a format that strtotime understands?
$firstOccurrence=strtotime($start);
$nextOccurence=strtotime("next $day", $firstOccurrence); //Set the first recurring date for this day
while($nextOccurence<=strtotime($activeUntil)){
echo date("M d, Y H:m:i",$nextOccurence)." | ";
$nextOccurence=strtotime("next $day", $nextOccurence);
}
Maybe it's time to start working with DateTime? It's pretty complex in modyfing dates. For example, creating date time from your $start would look like this:
$start="2014-04-29 11:00:00";
$dateTime=DateTime::createFromFormat("Y-m-d H:m:i", $start);
And as you have $dateTime, you can modify it by one day:
$dateTime->modify('+1 day');
//or just
$dateTime->modify('next tuesday');
//and return it as string
echo $dateTime->format("M d, Y H:m:i");
DateTime understands everything that strtotime does, so it can improve your solution. Try it out yourself, and let me know if this helps.
strtotime() can take 2 parameters. The first is the string and the second is the base timestamp.
Try the following:
// Assuming $startDateTime is a timestamp.
$followingDay = strtotime("next $repeatDay", $startDateTime);
Assume the date is:
$date = "2011-08-28";
It need to calculate 3 months previous to $date - how can that be done?
$new_timestamp = strtotime('-3 months', strtotime($date));
You can then use the new timestamp with the php date() function to display the new date how you wish, for example:
echo date("Y-m-d",$new_timestamp);
For me this way is much better because the code is more readable.
$datetime = Datetime::createFromFormat('Y-m-d', "2011-08-28");
$datetime->modify('-3 months');
echo $datetime->format('Y-m-d');
edit: I'm an idiot. You could do the above as follows
$datetime = new Datetime("2011-08-28");
$datetime->modify('-3 months');
echo $datetime->format('Y-m-d');
edit: As pointed out by calumbrodie, you can use the sub method instead of inverting the interval and adding it to the date object
I was trying to do something similar to the original question. I needed to subtract 1 day from a DateTime object. I know the other solutions work, but here's another way I liked better. I used this function:
function getPreviousDay($dateObject){
$interval = new DateInterval('P1D');
$dateObject->sub($interval);
return $dateObject;
}
$dateObject is a DateTime object that can have any date you wan't, but as I wanted the current date, I wrote:
$dateObject = new DateTime('now');
What my function does, is subtract 1 day from the date it receives, but you can modify it so it subtracts 3 months modifying the DateInterval constructor like this:
$interval = new DateInterval('P3M');
$dateObject->sub($interval);
return $dateObject;
You can find the explanation on the string format used in the DateInterval constructor here
DateInterval constructor documentation
There you'll se that letter 'P' (period) is mandatory, the you use an int to specify period length and then specify the period type, in the case of months 'M'. It looks as if there was an error in the documentation, it says that "M" is used for months and minutes, but it actually works for months. If you need to use minutes, you must specify "PTM", for example "PT3M" for 3 minutes, outside the table it says you must use the "T" identifier for time intervals.
edit:
To give a complete example, you have to use this format for a full date time interval:
$format = 'P1Y2M4DT2H1M40S';
This will represent an interval of 1 year, 2 months, 4 days, 2 hours,1 minute and 40 seconds
Hope this helps someone
<?php
$threemonthsago = mktime(0, 0, 0, date("m")-3, date("d"), date("Y"));
?>
<?php
$date = date_create('2000-01-01');
date_add($date, date_interval_create_from_date_string('10 days'));
echo date_format($date, 'Y-m-d');
?>
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Difference between dates
How to calculate the date difference between 2 dates using php
So, I have two dates. For instance, 2010-09-24 and 2010-09-25. I want to check if between those two dates the difference is 1 day.
I don't need to get a value of 86400 which means one day in seconds.
Don't forget that it can be 28, 28, 29, 30, 31 days in month.
Thanks.
What I have right now, but it doesn't work when there is difference between months:
$strto = strtotime($date);
$d1 = date('d', $strto);
$d2 = date('d', time());
echo $d2- $d1;
You can use strtotime to get the number of seconds in between
echo abs(strtotime('2010-09-24') - strtotime('2010-09-25'));
Don't use the day value - (eg date('d', ...)) - leave it as an integer (the result of strtotime()). Then subtract those dates, and then get the floor(difference / 86400).
Like so:
$dt = strtotime($date);
echo floor(abs(time() - $dt) / 86400);
You can do this nicely with the DateTime class if you have PHP 5.3:
<?php
$datetime1 = new DateTime('2010-09-25');
$datetime2 = new DateTime('2010-09-26');
$interval = $datetime1->diff($datetime2);
$intervaldays = (int) $interval->format('%R%d'); // %R signs the result +/-
This is probably less efficient than using strtotime methods, but it is very readable.
Why are you using date('d'... which returns the day of the month?
strtotime will create a UNIX-timestamp which is exactly what time() returns, so abs(time() - strtotime($date)) should already do the job. This way you don't have to worry how many days a month has as you're only working with timestamps.
This will get you the number of (complete) days:
floor( abs(time() - strtotime($date)) / 86400 )
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How to find number of days between two dates using php
Is there a quick and easy way to calculate the difference in days between two date strings in this format (YYYY-MM-DD) with PHP (not MySQL)?
$date1 = new DateTime("2010-07-06"); //inclusive
$date2 = new DateTime("2010-07-09"); //exclusive
$diff = $date2->diff($date1);
echo $diff->format("%a"); //3
(PHP 5.3 and higher only)
The only solution I see for PHP < 5.2 is to loop:
strtotime("-1 days");
strtotime("-2 days");
...
strtotime("-n days");
until we get to the unix timestamp of the first date. That's conceptually, you can do it in a much more efficient way, by first guessing the number of days with the timestamp difference of the two days and then testing the neighborhood.
Why dividing by 86400 doesn't work
date_default_timezone_set("Europe/Lisbon");
$date1 = strtotime("2010-03-28");
$date2 = strtotime("2010-03-29");
echo ($date2-$date1)/86400; //gives 0.95833333333333
$date1 = strtotime("2010-10-31");
$date2 = strtotime("2010-11-01");
echo ($date2-$date1)/86400; //gives 1.0416666666667
As Gordon correctly has pointed out, dividing by 86400 would be a valid solution for this problem if the timezone was set to 'UTC' before – just don't forget to restore it to the previous value after.
You can use this function to get the number of days between two date("Y-m-d H:i:s"):
function dateDiff($dateStart, $dateEnd)
{
$start = strtotime($dateStart);
$end = strtotime($dateEnd);
$days = $end - $start;
$days = ceil($days/86400);
return $days;
}
Copied from the Duplicate I've linked below the question.
The following SO questions might be of some help:
How to calculate the date difference between 2 dates using php
Dates difference with php
Calculate the difference between date/times in PHP
Date Difference in php?
Getting the difference between two time/dates using php?
More >>