This question already has answers here:
How to calculate the difference between two dates using PHP?
(34 answers)
Closed 9 years ago.
I will ask the user to enter start date and end date. I would want to get all of the dates from start to end and get the number of days between those dates. How can I do this in PHP given start and end date.
When dealing with dates, you can convert to timestamps (seconds) as Ignacio recommends. But generally if possible you will be better off working with actual dates & days at a higher level.
For this, see the DateTime class built into PHP:
http://www.php.net/manual/en/class.datetime.php
http://www.php.net/manual/en/class.dateinterval.php
These are well supported in PHP 5.2, but PHP 5.3 adds even better DateTime handling functionality.
End result of this code will be number of days.
$days = (strtotime(date("Y-m-d"))-strtotime("2010-08-20")) / (60 * 60 * 24);
echo $days;
Read my answer to this topic, with examples:
Calculate number of hours between 2 dates in PHP
Depending on the input the user gives, I would most likely be using something like
$dateOne = (int)(mktime(0, 0, 0, $month1, $day1, $year1)/86400); //Get the first date as a unix timestamp, then convert to days.
$dateTwo = (int)(mktime(0, 0, 0, $month2, $day2, $year2)/86400); //Get the second date as a unix timestamp, then convert to days.
// Example
//$dateOne = (int)(mktime(0,0,0,12,03,2009)/86400);
//$dateTwo = (int)(mktime(0,0,0,08,19,2011)/86400);
$daysBetween = $dateTwo-$dateOne; //Calculate days between.
echo $daysBetween.'<br />'; //Echo the days between.
for ($i=1; $i=$daysBetween; $i++) { //Loop through every day between, echo the date of that day.
echo date('Y-m-d', $dateOne*86400+($i*86400)).'<br />';
}
The above code will give you all the days, including the first and last date. To get only the ones in between change:
for ($i=1; $i=$daysBetween; $i++) { //Loop through every day between, echo the date of that day.
to:
for ($i=2; $i<=$daysBetween; $i++) { //Loop through every day between, echo the date of that day.
Have tested, works well.
NOTE: the first date MUST be before the last date.
Cheers
Charlie
Convert both dates to timestamps, then count from one to the other, converting back to dates.
Related
Is there any way to get the full date from a string that does not actually contain the month?
i am given the date in a format of Wednesday 16th and need to add this to my database with a month,
The application i am making is for lifestyle couriers and they get their manifests in that format and have the last 2 months available, so i need to find out the month?
Assuming that you want to regard the current and the last two months, I can imagine, that there will be no two day numbers of the same week day in that timespan (that should be proven first).
I would iterate back over the last n days using PHP's date function and try to detect your "Wednesday 16th" where n is the aggregate of month days that date with param "t" returns for the current and the last two months.
If you have your match then, you know the month and the year (the year could be the previous year as well if you start in January or February).
You can do it like this:
<?php
$date = 16;
$day = "Wednesday";
$oneMonthAgo = explode(" ",date("m Y F",strtotime("-1 month")));
$twoMonthsAgo = explode(" ",date("m Y F",strtotime("-2 months")));
if (date("l",strtotime($date."-".$oneMonthAgo[0]."-".$oneMonthAgo[1]))==$day) {
echo "Last month: ".$oneMonthAgo[2];
}
else if (date("l",strtotime($date."-".$twoMonthsAgo[0]."-".$twoMonthsAgo[1]))==$day) {
echo "Month before last: ".$twoMonthsAgo[2];
}
else {
echo "Not valid";
}
?>
Explanation
Because you are using PHP, there is an easy way to do this. In other languages, you would have to use a weekday algorithm.
In PHP, we can convert a properly formatted string into a time, from which we can then derive date information. Examples of a properly formatted string is -1 month or -2 months, which return time objects for the previous month or the month before that, respectively.
Using the date() function, we can get the month, year and textual month values for those months. We delimiter these by a space, so that we can explode these values into an array after they are found. Thus, we now have two arrays, $oneMonthAgo and $twoMonthsAgo, which both contain their month's respective number, year and textual month at the 0, 1 and 2 indexes respectively.
Now, we can create another time, by appending the date that we are looking for ($date) onto these values, with the proper delimiters in-between (when using - as the delimiters, PHP assumes a d-m-Y format, when using / PHP assumes a m-d-Y format). Then, by passing that through another date() function, we can find the data that we are looking for: the textual day that took place at that date. Now we can simply compare that to the day that we are looking for, $day. If the textual day is the same, then this is the month which we are looking for, so we can print out the full textual month.
We do this in an if / else statement for both months, and if we still haven't found it, assume that the date is invalid.
Notes
References to the PHP functions used can be found on the PHP Manual: date() function, strtotime() function, Valid dates for strtotime()
Yes and no. Since full date requires month to be known you need to know what to do with lack of that information. If you "guess" the month (be it current one or random, does not matter), then "yes" is close. If you cannot tell what the month we talk about then answer is no (or random).
PS: you may need a year too...
I use a while loop to loop backwards however many months needed to find what is searched for.
$date = 16;
$day = "Wednesday";
$x=0;
$start = date("Y-m-") . $date;
While(date("l", strtotime($start ."-" .$x . "months")) != $day){
$x++;
}
Echo $x . " months ago.";
// Or to output the date:
//Echo date("Y-m-d", strtotime($start ."-" .$x . "months"));
https://3v4l.org/vUYeX
This will output 0 months ago.
But if input $date= 15; it will output 5 months ago (March 2017).
I only have basic PHP knowledge and I'm using PHP+Mysql and trying to check the difference in days between 2 dates; the 1st date is formatted by myself in the script as a string:
$f_entrega=$_POST['year1']."-".$_POST['month1']."-".$_POST['day1'];
The second date ($f_dock) which is the one causing the issue is taken from the mysql database which column is in DATE format. To compare the dates I do the following:
if(!empty($_POST["id"])){
$f_entrega=$_POST['f_entrega_a']."-".$_POST['f_entrega_m']."-".$_POST['f_entrega_d'];
$f_entr=$f_entrega;
$mysqli=conectar();
$resultado = $mysqli->query("SELECT id,f_dock FROM pt");
$row = $resultado->fetch_assoc();
for ($i=0;$i<count($ids);$i++){
do{
if ($ids[$i]==$row["id"]){
$f_dock=$row["f_dock"];
break;
}
} while ($row = $resultado->fetch_assoc());
$error=0;
var_dump($f_dock);
$f_dock=strtotime($f_dock);
$f_dock=date('Ymd',$f_dock);
$f_entrega=$f_entr;
$f_entrega=strtotime($f_entrega);
$f_entrega=date('Ymd',$f_entrega);
$f_dock=DateTime::createFromFormat('Ymd',$f_dock);
$f_entrega=DateTime::createFromFormat('Ymd',$f_entrega);
$dias_vendor=date_diff($f_dock,$f_entrega);
$tat=$dias_vendor->format('%R%a');
Sometimes it works correctly, but other times I get Warning: strtotime() expects parameter 1 to be string, object given in [first line] and $tat is not correctly calculated and has strange values.
I've tried different solutions like $f_dock=(string)$f_dock before but finally the convertion always fails in some cases. Thanks in advance for any tip.
The error that you are getting is because the string you are entering is not a valid string for the strtotime() function to convert.
For instance 2015-08-31 will convert just fine, as will today, tomorrow or +7 days.
For more specific help you will need to tell us what the value of $f_dock is (as Marcos says in his comment, var_dump($f_dock) will get you this).
However, on to the solution:
$date1 = strtotime($f_dock); //timestamp in seconds
$date2 = strtotime($f_entrega); //same for the second date
$difference = $date1 - $date2; //difference in seconds between the dates
$days = floor($difference/86400);
86400 is the number of seconds in a day, so find out how many seconds difference there is, then see how many days worth of seconds are in there and use floor() to round the number down. Job done.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP calculate person's current age
I want to find the persons age.
$time=$row['date_of_birth'];
$date=explode("-", $time);//gets the date birth from the database and puts it into an array
$a=getdate();//gets todays date
$diff_date= gregoriantojd($a["mon"],a["mday"],a["year"] ) - gregoriantojd(date[1],date[2],date[0]);//subtracts the differences between the dates, this is returned in seconds..
The question is whether this is the way to do it? and how do I convert the seconds and convert them to years (as an integer)?!
EDIT:
I think that the last line should be this:
return floor($diff_date /60*60*24*365);
Just try with strtotime (converts date string into timestamp):
$time = strtotime($row['date_of_birth']);
$age = date('Y', $time - time());
echo 'age: ' . $age;
If $time is supposed to be unix timestamp
$time=$row['date_of_birth'];
$date1 = new DateTime($time);
$date_diff = $date1->diff(new DateTime(), true);
$age = $date_diff->y;
I think you can make use of the date_diff function in PHP.
1st question: The question is whether this is the way to do it?
No. The function gregoriantojd (per the manual entry here) returns a value in days, not seconds. I like the date_diff conversion that Piotr gives the best.
2nd question: how do I convert the seconds and convert them to years
(as an integer)?!
Well, if you were starting with a number of seconds (which you aren't) then your second formula would be mostly correct, but of course it wouldn't account for leap-years. So for anyone older than 4, or at least 8, it would be off for one or more days around their birthday. Usually on their birthday is a pretty important time to get their age correct.
Is there a way to find out if a date falls within 7 days of the current date using PHP? If there is, would it also be possible to figure out how many days away that date is?
$date = strtotime('2010-11-28');
if (strtotime('-7 days') < $date && $date < strtotime('+7 days')) {
// yup
}
$difference = abs($date - time()) / 60 / 60 / 24;
Could be refined a bit if you care about edge cases, whole days and daylight-savings/leap seconds issues, but this should hopefully give you the right idea. Of course the Date class should be the preferred method to handle this, but it's only available in PHP 5.3+.
For the first one, add 7 days to the current date and see which is greater.
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-add
For the second one:
http://php.net/manual/en/function.date-diff.php
Hi guys I was wondering if anyone could help me with the following:
I have two dates entered in two different fields > startDate and endDate.
As they are entered I would like to show a warning if:
the second one is a date before the first one. So it is wrong.
and that between the first one and the second one there a minimum gap of at least 3 days during certain period of the year and 7 days during other periods of the year.
I was thinking to write a PHP function but how do I call it as soon as the second date is entered?
Many many thank for you help
Francesco
Convert your dates to Julian day with gregoriantojd.
/**
* Get the Julian day of a date. The Julian day is the number of days since
* January 1, 4713 BC.
*/
function datetojd($date)
{
return gregoriantojd(idate('m', $date),
idate('d', $date),
idate('Y', $date));
}
// you can use strtotime to parse a lot of date formats, assuming they are text
$startDate = strtotime('22nd Nov 2009');
$finishDate = strtotime('26nd Nov 2009');
$diff = datetojd($finishDate) - datetojd($startDate);
if ($diff < 0) {
// oops, $finishDate is before $startDate
}
else {
// check $diff is at least 3 or 7 depending on the dates
}
Do the check on the client side with Javascript.
Then perform the same checks server side which can present a message after the form has been submitted (for those few users running with Javascript disabled?).
I'm not sure if you can call it as soon as the second date is entered, unless you reload the page or have the function on another page which could get a tad complicated
The way i would check the dates is to use php's mktime function, which will give you the unix time. Then if the second one is less that the first, the second date is before and if the second one is less that the first + 3 * 24 *60 * 60 (seconds in 3 days) then it isn't 3 days apart
1° case:
SELECT [whatever you need from the table] WHERE endDate < startDate
2°case:
SELECT [whatever you need from the table] WHERE (endDate - startDate) >= IF([select that define in wich period of the year the data are],3, 7)
This ill do the trick, but probably your problem cant be solved sql-side.
Please, describe better what you need to do.
EDIT:
Ok, then as someone else suggested, first check htem by js (for convenience, not for safely: never rely only on js validation!)
Use strtotime for the comparison/operation.
EDIT2 (last;) :
Go with Alex's Answer