How to re-format number to time in php? - 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.

Related

Subtracting hours and minutes from input fields

I have a form that has five input fields:
name="MultiRoomFromDate" //outputs the date in the following format "d-m-Y"
name="MultiRoomFromTimeH" // has a dropdown of "00" to "23"
name="MultiRoomFromTimeM" // has a dropdown of "00" to "59"
<select name="MultiFromDisplayTimeH" id="MultiFromDisplayTimeH" class="FormTime">
<option value="0">0</option>
<option value="3600">1</option>
<option value="7220">2</option>
<option value="10800">3</option>
<option value="14400">4</option>
</select>
<select name="MultiFromDisplayTimeM" id="MultiFromDisplayTimeM" class="FormTime">
<option value="0">0</option>
<option value="900">15</option>
<option value="1800">30</option>
<option value="2700">45</option>
</select>
If I select the "MultiRoomFromDate" as 26-01-2020" and the MultiRoomFromTimeH as "09" and the MultiRoomFromTimeM as "00" and the select the "MultiFromDisplayTimeH" as "01"and the "MultiFromDisplayTimeM" as "00" and submit the form the output is:
FromDate = MultiRoomFromDate; //26-1-2020
FromHours = MultiRoomFromTimeH; //09
FromMins = MultiRoomFromTimeM; //00
DisplayHours = MultiFromDisplayTimeH; //3600
DisplayMins = MultiFromDisplayTimeM; //0
What I need to do is output the "FromDate, FromHours, FromMins" MINUS the "DisplayHours" and "DisplayMins" as Y-m-d H:i.
This is what I have been working with:
$MultiRoomFromDate = trim($_POST['MultiRoomFromDate']);
$MultiFromDisplayTimeH = trim($_POST['MultiFromDisplayTimeH']);
$MultiFromDisplayTimeM = trim($_POST['MultiFromDisplayTimeM']);
$FromdateStamp = strtotime($MultiRoomFromDate);
$TodateStamp = strtotime($MultiRoomToDate );
$DisplayTime = $FromTimeStamp - $FromDisplayHours - $FromDisplayMins;
$DisplayDateTime = date("Y-m-d H:i", $DisplayTime);
$RoomFromTime = $MultiRoomFromTimeH.":".$MultiRoomFromTimeM;
if(!empty($MultiFromDisplayTimeH)) {
$DisplayTime1 = date('Y-m-d H:i:s', strtotime("-". $MultiFromDisplayTimeH." hours", strtotime($MultiRoomFromDate." ". $RoomFromTime)));
}
if(!empty($MultiFromDisplayTimeM)) {
$DisplayTime = date('Y-m-d H:i:s', strtotime("-". $MultiFromDisplayTimeM." minutes", strtotime($DisplayTime1)));
}
if(empty($MultiFromDisplayTimeH) && empty($MultiFromDisplayTimeM)){
$DisplayTime = date('Y-m-d H:i', strtotime($DisplayDateTime));
}
Also tried:
$t = $MultiFromDisplayTimeH + $MultiFromDisplayTimeM;
$RoomFromTimeStamp = strtotime($MultiRoomFromDate);
$h = $RoomFromTimeStamp - $t;
$DisplayTime = date("Y-m-d H:i:s",$h);
First, simplify your select option syntax by removing the value attributes -- it only makes your markup harder to comprehend at a glance and it will not be necessary for the datetime calculation that I will later demonstrate. I also think simpler field names would be beneficial.
<select name="subtractHours" class="FormTime">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
<select name="subtractMinutes" class="FormTime">
<option>0</option>
<option>15</option>
<option>30</option>
<option>45</option>
</select>
Then, use PHP's datetime class to:
Initialize a datetime object from your date/time values
Subtract the submitted amount of time
Adjusted datetime string into the desired format.
Code: (Demo)
$fromDate = '26-1-2020';
$fromHours = '09';
$fromMins = '00';
$subtractHours = '1';
$subtractMins = '0';
$format = 'Y-m-d H:i:s';
$date = DateTime::createFromFormat('d-m-Y H:i:s', "{$fromDate} {$fromHours}:{$fromMins}:00");
$date->sub(new DateInterval("PT{$subtractHours}H{$subtractMins}M"));
echo $date->format('Y-m-d H:i');
Output:
2020-01-26 08:00
I added the :00 as seconds to the object for stability/consistency in case you wanted to insert the full datetime stamp into your database (which will require Y-m-d H:i:s format).
The above will process just as well when the time subtraction results in losing a day. (Demo)
$fromDate = '25-1-2020';
$fromHours = '01';
$fromMins = '30';
$subtractHours = '6'; // don't bother with 3600 precalculation
$subtractMins = '45';
// Output: 2020-01-24 18:45
I completely rewrote my code and I have now resolved the issue by using the following code:
$DisplayTime = $FromTimeStamp - $FromDisplayHours - $FromDisplayMins;
echo "DISPLAYTIME 1 ".$DisplayTime."<br/>";
$DisplayDateTime = date("Y-m-d H:i", $DisplayTime);

MySql alternative to PHP date interval

I'm trying to create a report which is kinda complicated(at least to me) because it will allow the user to choose an interval for the report, and group by smaller intervals e.g. every day, every week, every two weeks, every month, every quarter and so on. I found how I can generate interval table columns using PHP DatePeriod and and DateInterval functions, but now I'm stuck to convert to MySql in order to match the db columns with html table columns generated by PHP.
<select class="form-control" id="columns" name="columns" tabindex="-1" aria-hidden="true">
<option value="1 day" selected="">Each day</option>
<option value="1 week">Each week</option>
<option value="1 month">Each month</option>
<option value="3 months">Each quarter</option>
<option value="1 year">Each year</option>
</select>
This is the select option for choosing how the report is gonna be grouped and:
$cols = array();
$colsIdentifiers = array();
$start_date = \Carbon\Carbon::parse(request('start_date'));
$end_date = \Carbon\Carbon::parse(request('end_date'));
$interval = DateInterval::createFromDateString(request('columns'));
$period = new DatePeriod($start_date, $interval, $end_date);
foreach ($period as $dt) {
$cols[] = $dt->format("d-m-Y");
$colsIdentifiers [] = $dt->format("dmY");
}
This is the php code to generate the cols.
How can do the same but in Mysql??
I think that you can only use the BETWEEN SQL command to solve your problem. Your database don't need to know what are these importants dates, but only persists these data.
Try do it:
<?php
$sql = "SELECT id, name, something";
$sql .= "FROM table";
$sql .= "WHERE datefield BETWEEN :minvalue AND :maxvalue";
$stmt = $pdo->prepare($sql);
$stmt->execute([':minvalue' => $minLimit, ':maxvalue' => $maxLimit]);
$data = $stmt->fetchAll();
foreach($data as $item) {
// do something with your new set.
}
Hope that help you.

PHP Loop for Year Dropdown

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

Converting String into Date from HTML Form

i collect date formats like this :
Day
<select id="DOBDay" name = "DOBDay" class="pure-input-1-4">
<option>Date Of Birth Day</option>
<option value="01">01</option>
Month
<select id="DOBMonth" name = "DOBMonth" class="pure-input-1-4">
<option>Date Of Birth Month</option>
<option value="06">06</option>
Year
<select id="DOBYear" name = "DOBYear" class="pure-input-1-4">
<option>Date Of Birth Year</option>
<option value="2000">2000</option>
After the form has been posted ,it gets collects like this :
$DOBDay = $_POST['DOBDay'];
$DOBMonth = $_POST['DOBMonth'];
$DOBYear = $_POST['DOBYear'];
How do i get this into a dateformat to be stored into a MySQL date feild.
I have searched the web and cannot find this example anywhere for assistance.
Try this :
$DOBDay = '21';
$DOBMonth = '09';
$DOBYear = '1986';
$full_date = $DOBYear.'-'.$DOBDay.'-'.$DOBMonth;
echo $full_date;`
A lot of possibilities.. mktime for example.
// if you need a timestamp
$timestamp = mktime(0,0,0,$DOBMonth, $DOBDay, $DOBYear);
// or datetime
$datetime = date("Y-m-d", $timestamp);
mysql use yyyy-mm-dd format. so you should store the value in something like :
$DOBDay = '21';
$DOBMonth = '09';
$DOBYear = '1986';
$date = $DOBYear.'-'.$DOBMonth.'-'.$DOBDay;
echo $date;
$date= $_POST['DOBDay']."/". $_POST['DOBMonth']."/".$_POST['DOBYear'];

Date Calculation

i have a form with a fix date and time entry. (eg: 23:30 - 04/14/2011)
i have a second time entry. (eg: 00:15 - the Next Day)
how can i calculate the Date of the second entry time.
with only on these 3 variables.
Time A = 23:30 on the 04/14/2011
Time B = 00:15 on the ____ ?
Can anyone show me the semantics of this calculation how to find the Date of Time B!
Thanks
I can see a couple of ways of doing this. I would probably do something like this:
In HTML (missing form controls, labels etc):
<input name="date_from" type="text"> <!-- use some sort of javascript date popup control to format this properly-->
<input type="text" name="hours_to"> <!-- remember to add validation to input -->
<input type="text" name="mins_to"> <!-- remember to add validation to input -->
<select name="day_to">
<option value="0">The same day</option>
<option value="1">The next day</option>
<option value="2">The day after that</option>
</select>
Then in your PHP form handler, assuming date_from is in a valid date format:
$time_from = strtotime($_POST['date_from']);
$time_to = str_to_time('Y-m-d 00:00:00', $time_from) //start of the day
+ 86400 * (int) $_POST['day_to'] //86400 seconds in a day
+ 3600 * (int) $_POST['hour_to'] //3600 seconds in an hour
+ 60 * (int) $_POST['min_to']; //60 seconds in a minute
$sql_from = date("Y-m-d H:i:s", $time_from);
$sql_to = date("Y-m-d H:i:s", $time_to);
Then you can do your db insert, subject to validations etc of course.
Also, strtotime() can accept relative time parameters (e.g. '+ 1 day') which might be another way of doing this, check the PHP manual for more info
var date1 = '23:30 - 04/14/2011';
var date2 = '00:15 - the Next Day';
var d1month = date1.split(' - ')[1].split('/')[0];
var d1day = date1.split(' - ')[1].split('/')[1];
var d1year = date1.split(' - ')[1].split('/')[2];
var d1hour = date1.split(' - ')[0].split(':')[0];
var d1min = date1.split(' - ')[0].split(':')[1];
var d2hour = date2.split(' - ')[0].split(':')[0];
var d2min = date2.split(' - ')[0].split(':')[1];
var d = new Date(d1year, parseInt(d1month)-1, d1day, d1hour, d1min, 0, 0);
var d2 = new Date(d1year, parseInt(d1month)-1, parseInt(d1day)+1, d2hour, d2min, 0, 0);

Categories