How to find the dates between two specified date?
If I have two dates 20-4-2010 and 22-4-2010 in two text box and I want the dates to be like this 20, 21, 22. How do I get that ?
I am pretty sure this has been answered a quadrillion times before, but anyway:
$start = strtotime('20-04-2010 10:00');
$end = strtotime('22-04-2010 10:00');
for($current = $start; $current <= $end; $current += 86400) {
echo date('d-m-Y', $current);
}
The 10:00
part is to prevent the code to skip or repeat a day due to daylight saving time.
By giving the number of days:
for($i = 0; $i <= 2; $i++) {
echo date('d-m-Y', strtotime("20-04-2010 +$i days"));
}
With PHP5.3
$period = new DatePeriod(
new DateTime('20-04-2010'),
DateInterval::createFromDateString('+1 day'),
new DateTime('23-04-2010') // or pass in just the no of days: 2
);
foreach ( $period as $dt ) {
echo $dt->format( 'd-m-Y' );
}
You can use mktime()
.
mktime() is useful for doing date arithmetic and validation, as it will automatically calculate the correct value for out-of-range input.
If you increment the day number you get a valid date back, even if you go past the end of the month:
<?php
$day= 25;
$dateEnd = mktime(0,0,0,5,3,2010);
do {
$dateCur = mktime(0,0,0,4,$day,2010);
$day++;
print date( 'd-m-y', $dateCur) .'<br>';
} while ($dateCur < $dateEnd);
Output:
25-04-10
26-04-10
27-04-10
28-04-10
29-04-10
30-04-10
01-05-10
02-05-10
03-05-10
You can do:
$start = strtotime("2010-04-20"); // get timestamp for start date.
$end = strtotime("2010-04-22"); // get timestamp for end date.
// go from start timestamp to end timestamp adding # of sec in a day.
for($t=$start;$t<=$end;$t+=86400) {
// get the date for this timestamp.
$d = getdate($t);
// print the date.
echo $d['mday'].'-'.$d['mon'].'-'.$d['year']."\n";
}
Output:
20-4-2010
21-4-2010
22-4-2010