Reputation: 10771
I need to populate a drop-down list on a form with dates for all Mondays in the next year?
What is the best way to do this? With a MySQL table populated with dates or is there a smarter method of generating these dates without the need for MySQL?
Desired output would be something like:
The value of the selected option would just be the date commencing, so for the first option in the image, 11 Mar 13
would be the value.
Thanks for the help and apologies if this is a silly question.
Upvotes: 0
Views: 2778
Reputation: 212412
Edit: Modified to support passing in a start date rather than simply a year
function getDays($year, $startMonth=1, $startDay=1, $dayOfWeek='monday') {
$start = new DateTime(
sprintf('%04d-%02d-%02d', $year, $startMonth, $startDay)
);
$start->modify($dayOfWeek);
$end = new DateTime(
sprintf('%04d-12-31', $year)
);
$end->modify( '+1 day' );
$interval = new DateInterval('P1W');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("d/m/Y") . '<br />';
}
}
getDays(2013, 3, 12, 'monday');
Formatting of the output as a dropdown should be a straightforward exercise
Upvotes: 3
Reputation: 3773
This code will output a list of the dates you want
for($i = 0; $i <= 365; $i ++){
$startdate = strtotime("today + $i day");
$enddate = strtotime("today + " . ($i + 6) . " day");
if(date('D', $startdate) == 'Mon'){
echo date('d M y', $startdate) . " to " . date('d M y', $enddate) . "\n";
}
}
To have this display as a dropdown list you would need to add the HTML to it like this
<select id="date" name="date">
<?
for($i = 0; $i <= 365; $i ++){
$startdate = strtotime("today + $i day");
$enddate = strtotime("today + " . ($i + 6) . " day");
if(date('D', $startdate) == 'Mon'){
echo '<option value="' . date('d-m-Y', $startdate) . '">' .date('d M y', $startdate) . " to " . date('d M y', $enddate) . "</option>";
}
}
?>
</select>
I have given the value
of the select option the date of the Monday in dd-mm-yyyy
format so when dealing with the form once submitted you will have the Monday which was selected.
So if you were to select the row 27 May 13 to 02 Jun 13
and submit the form the php file on the other end of the form would have the variable $_POST['date']
and it's value would be 27-05-2013
.
Upvotes: 1
Reputation: 14163
You could simply use PHP
and then the DateTime::add method. Then you can take the first monday of the year and use the method to add 7 days 52 times. That will give you all mondays. If you add 6 days you get the till date.
Upvotes: 1