PHP Loop for Year Dropdown - php

I am trying to create a HTML select input based on months/years and I am not sure the best approach for it.
While creating a standard loop of years was the first place I started, I wasn't sure how to get the last days of each of the month/years in order to create the values.
Is there any built in PHP functions that can accomplish something close to what I am looking for?
Logic:
Must be able to provide a starting year (ex. 2014).
Must start at the starting year and go 1 year past the current year (ex. If Start = 2014, it will show 2014, 2015, 2016.
The value of the option must be the last day of the month in date format (ex. <option value="01/31/2015">January 2015</option>
Output:
<select class="s2 span4" name="desiredCompletion" placeholder="Select a Desired Completion Date">
<optgroup label="2016">
<option value="01/31/2016">Janurary 2016</option>
<option value="02/28/2016">Feburary 2016</option>
<option value="03/31/2016">March 2016</option>
...
</optgroup>
<optgroup label="2015">
<option value="01/31/2015">Janurary 2015</option>
<option value="02/28/2015">Feburary 2015</option>
<option value="03/31/2015">March 2015</option>
...
</optgroup>
<optgroup label="2014">
<option value="01/31/2014">Janurary 2014</option>
<option value="02/28/2014">Feburary 2014</option>
<option value="03/31/2014">March 2014</option>
...
</optgroup>
</select>

This function should do:
function createYearSelect($from) {
// open select
echo "<select class=\"s2 span4\" name=\"desiredCompletion\" placeholder=\"Select a Desired Completion Date\">";
// for each year from the one specified to the one after current
foreach(range($from, date('Y') + 1) as $year) {
// open optgroup for year
echo "<optgroup label=\"$year\">";
// foreach month
foreach (range(1, 12) as $month) {
// timestamp of first day
$time = strtotime("$year-$month-01");
// create option with date() formatting
echo "<option value=\"".date("m/t/Y", $time)."\">".date("F Y", $time)."</option>";
}
// close optgroup for year
echo "</optgroup>";
}
// close select
echo "</select>";
}

Here's a bit more elegant way
foreach(range(2014, 2015) as $year){
foreach(range(1, 12) as $month){
echo date('Y.m.d', strtotime('Last day of ' . date('F', strtotime($year . '-' . $month . '-01')) . $year)) . PHP_EOL;
}
}
This outputs the list of the last days of months for the years in specified range.
2014.01.31
2014.02.28
2014.03.31
2014.04.30
...

Using the DateTime class you can create dates using natural language.
Eg,
$date = new DateTime("-1 Year");
echo $date->format('F Y'); // Prints 'December 2014'
You can use a decrementing for loop to create many dates going back in time.

Check for the function below which gives the total number of days in a month
date("t");
Further details are available at http://php.net/manual/en/function.date.php

Related

How to re-format number to time in php?

I am creating a room booking system with some information like End-user needs to select in difference inputs
Date booking
Time booking (custom fixed value (08:00, 08:30,... ...17:30) store into database as number (800,830 ...n)
End-user need to tell how many hours need to book.( 1hr, 1hr 30, 2hr ...8hr) per day/date (The hour here will calculate in minute like 1hre = 60min, 2hrs = 120min ...n)
Base on above information, I would like to dynamic calculate the end time of the meeting. Let said, end user select booking date= 2022-02-05, start-time = 08:30 and select duration = 1hr 30min. Of course the end time is 10:00 but how to calculate the end time?
Here is my html code
<input type="date" class="form-control" id="bookingdate" name="bookingdate" placeholder="dd/mm/yyyy" required>
<select id="selecttime" name="selecttime" style="width: 130px !important;" class="rounded-right text-center bd-outline" required data-header="Select a dept" onfocus="document.getElementById('errtxt').innerText='';">
<option disabled="disabled" selected="selected">Start time</option>
<option value="08:00">08:00</option>
<option value="08:00">08:30</option>
<option value="09:00">09:00</option>
<option value="09:30">09:30</option>
<option value="17:30">17:30</option>
</select>
<select id="duration" name="duration" style="width: 120px !important;" class="rounded-right text-center bd-outline" required ">
<option disabled="disabled" selected="selected">Select</option>
<option class="text-start text-secondary" value="30">30 min</option>
<option class="text-start" value="60">1 hr</option>
<option class="text-start text-secondary" value="90">1hr 30min</option>
<option class="text-start" value="120">2 hrs</option>
<option class="text-start text-secondary" value="510">8hrs 30min</option>
</select>
And here is my php code after post the html form
$Booking_Date = $_POST["bookingdate"];//let said val = 2022-02-05
$Booking_Time = $_POST["selecttime"];//val like 08:00, 08:30 ...
$Duration = $_POST["duration"]; //val like 30min, 60min, 90min,....450min
As of this code I have no idea to capture end time of the meeting
I tried this but I think it will have something better because I will store each value separately into database and I think PHP will have other function/choice that I don't know ....
$StartTime = new DateTime($Booking_Date . $Booking_Time);
$minutesToAdd = $Duration;
echo "Start time " . $StartTime->format('Y-m-d H:i');
$StartTime->modify("+{$minutesToAdd} minutes");
echo "<br />End time " . $StartTime->format('H:i');
Could anyone suggest me other better idea?
Thank you in advance.
You can use strtotime like so:
$Booking_Date = "2022-02-05";
$Booking_Time = "08:30";
$Duration = "30min";
$Duration_minutes = str_replace("min", "", $Duration); // Removes "min"
// Store this value in your database
$booking_datetime = $Booking_Date . " " . $Booking_Time; // Assumes 24h format
// Store this value in your database under DATETIME format
$meeting_end_timestamp = strtotime($booking_datetime) + $Duration_minutes * 60; // Adds duration in seconds
$meeting_end = date("Y-m-d H:i:s", $meeting_end_timestamp); // Convert timestamp to formatted date
echo $meeting_end; // Outputs "2022-02-05 09:00:00"
If you want to change the output's format: see documentation.

How Display Month which is Start with Current Month Using PHP?

I want to display all month with current year but it must be start with current month like below.
I need like if current month October and year 2019 then option list should be start with 2019-10 then all renaming month with current year like below.
Output
<select>
<option value="">SELECT MONTH</option>
<option value="2019-10">October-2019</option>
<option value="2019-11">November-2019</option>
<option value="2019-12">December-2019</option>
<option value="2019-01">January-2019</option>
<option value="2019-02">February-2019</option>
<option value="2019-03">March-2019</option>
<option value="2019-04">April-2019</option>
<option value="2019-05">May-2019</option>
<option value="2019-06">June-2019</option>
<option value="2019-07">July-2019</option>
<option value="2019-08">August-2019</option>
<option value="2019-09">September-2019</option>
</select>
It's Working and give me exact output as i want.
<select>
<option value="">SELECT MONTH</option>
<?php
for ($i = 0; $i < 12; $i++)
{
$getMonth = strtotime(sprintf('%d months', $i));
$monthLabel = date('F', $getMonth)."-".date("Y");
$monthval = date("Y")."-".date('m', $getMonth); ?>
<option value="<?php echo $monthval; ?>"><?php echo $monthLabel; ?></option>
<?php }
?>
</select>
With this PHP code you can get current_month
date_default_timezone_get();
$month= date('Y-m', time());
Then you simply need to fill your 'select' tag with options in the correct order
Use the DateTime class. Create an array as follows:
$dt = date_create('first Day of this Month 00:00'); //start
$valueCaption = [];
$numberOptions = 5;
for($i=0;$i<$numberOptions;$i++){
$valueCaption[$dt->format('Y-m')] = $dt->format('F-Y');
$dt->modify('+1 Month');
}
returns a array $valueCaption how
array (
'2019-10' => "October-2019",
'2019-11' => "November-2019",
'2019-12' => "December-2019",
'2020-01' => "January-2020",
'2020-02' => "February-2020",
)
You use this array when outputting with a foreach ($valueCaption as $value => $caption) to create your options.

PHP Appending year the select menu

I have this custom function in place, It will get the current year from the date function in php. When next year will come I want to append next year with previous year.
Example:
Current Year is "2013"
Next year will be "2014"
When year will come, It should dynamically add 2014 to drop-down list.
<select>
<option>2014</option>
<option>2013</option>
</select>
function ec_year(){
$year = date("Y");
}
Anyone any help please.
Use this :
$start_year = '2013';
$current_year = date("Y");
echo '<select>';
for ($i=$start_year; $i <= $current_year; $i++) {
echo '<option>' . $i .'</option>';
}
echo '</select>';
Try this give the end year as you like ...it will automatically work on present year
<select>
<?php for($i=date(Y);$i>=endyear);$i--){
<option><?php echo $i;?></option>
<?php }?></select>
Try this:
<select>
<option><?php print(Date("Y") + 1); ?></option>
<option><?php print(Date("Y")); ?></option>
</select>
Try:
echo date('Y')+1; #will give current year + 1

How to validate select with PHP?

How to validate day/month/year select with php? I red some topics about who to validate select with 2-3 or even 5-6 select options. I would know how to validate that kind of select. But in the case of, for exemple, month, there are 32 options. Or in the case of year option, the are 60-70 options. So im interested in whats the optimal way to do select validation when you have so much options?
For date it's actually relatively easy - you just use checkdate().
And for the other cases you could check if the value is within an expected range like:
if ($val >= min && $val <= max)
or, in case you have all the values in an array
if (in_array($val, $array_of_valid_values))
Validating selects is fairly trivial.
Year
Let's say you have a sequential range of years from 1960-2013.
Your HTML for the selects is:
<select name="year">
<option value="1960">1960</option>
...
<option value="2013">2013</option>
</select>
So, you know that your year has to fall in the range of 1960 to 2013:
$year = (int) $_POST["year"]);
if ($year < 1960 || $year > 2013) {
$validationPassed = false;
}
Simple enough to validate the year.
Month
Now that you know what year it is, you can find out if it is a leap year. However, that is only important for a single month, so first let's validate what month they selected:
<select name="month">
<option value="0">January</option>
...
<option value="11">December</option>
</select>
Once again, validation of the month is easy. We know it has to be a value between 0 and 11.
$month = (int) $_POST["month"];
if ($month < 0 || $month > 11) {
$validationPassed = false;
}
Day
Now we know the month and the year. to validate the selected day, we need to check the following criteria:
Is it a leap year?
Is it the month of the year with the extra day for the leap year? (February).
For a year to be a leap year, it has to be divisible by 400, or not divisible by 100 and divisible by 4:
function isLeapYear($year) {
if ($year % 400 == 0)
return true;
else if ($year % 100 == 0)
return false;
else if ($year % 4 == 0)
return true;
return false;
}
Now, we can check if it is a leap year or not. If it is a leap year, then we know we need to allow 1 extra day in February.
We make an array of days in each month:
$daysInMonth = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
Then we get the amount of days in the current month:
$monthDays = $daysInMonth[$month];
If it is a leap year, we add a day to the total days in the month:
if ($month == 1 && isLeapYear($year)) //February
$monthDays++;
Finally, we can validate the day
$day = (int) $_POST["day"];
if ($day < 0 || $day > $monthDays) {
$validationPassed = false;
}
Now, all of this is basically encapsulated into the checkdate() function that was in the other answer below. So, to use checkdate() instead of all the code above, you could simply do the following:
HTML
(Note: checkdate() is not zero-based, so we start our days and months at 1 instead of 0.)
<form action="myphp.php" method="post">
<select name="day">
<option value="1">1</option>
...
<option value="31">31</option>
</select>
<select name="month">
<option value="1">1</option>
...
<option value="12">12</option>
</select>
<select name="year">
<option value="1960">1960</option>
...
<option value="2013">2013</option>
</select>
</form>
PHP
$day = (int) $_POST["day"];
$month = (int) $_POST["month"];
$year = (int) $_POST["year"];
$validationPassed = checkdate($month, $day, $year);

PHP - Displaying multiple years from the current year

I was wondering if someone could help me.
I want to display a dropdown ( select ) box with 10 years starting with the current year.
I know displaying the year is done by using
date("Y");
But im not sure how to display the 10 years after that automatically.
Any help would be greatly appreciated.
Cheers
Try:
echo('<select name="year">');
for ( $i = date("Y"); $i < date("Y")+11; $i++ )
{
echo('<option value="'.$i.'">'.$i.'</option>');
}
echo('</select>');
See result here http://codepad.viper-7.com/8S0Ogi
PHP has a slew of Date/Time functions.
One you have instantiated a DateTime Object, you'll be able to manipulate any date or time using simple date_add or date_sub functions...
However, for your situation, it would be possible and a lot simpler to simply iterate over the number of years you want in the dropdown and simply increase the value for each option.
$yearSpan = 10;
$currentYear = date("Y");
$html = '<select id="foobar">';
for($i = $currentYear; $i<=$yearSpan; $i++) {
$html .= "<option value='".$i."'>".$i."</option>";
}
$html .= '</select>';
That should populate $html with content similar to this -
<select id="foobar">
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
...
<option value="2021">2021</option>
<option value="2022">2022</option>
</select>
You can try with this:
<select>
<option>Select One</option>
<?php
$year = date("Y");
$yearto = date("Y")+10;
while ($year <= $yearto)
{
echo "<option value='".$year."'>".$year."</option>";
$year++;
}
?>
</select>

Categories