Subtracting hours and minutes from input fields - php

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);

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 to add 3 drop down in single variable in php?

Two days ago I had an interview as a php developer and they gave me a task to perform.
I completed 90% of the task, but I failed while trying to add date, month and year together.
I have 3 dropdowns for date, month and year:
Date Of Birth : <br />
Date : <select name="date">
<?php $i=1; for($i=1; $i<=31; $i++){ ?> <option> <?php echo $i?> </option> <?php } ?>
</select>
Month : <select name="month">
<option value="January">January</option>
<option>Febuary</option>
<option>March</option>
<option>April</option>
<option>May</option>
<option>June</option>
<option>July</option>
<option>August</option>
<option>September</option>
<option>October</option>
<option>November</option>
<option>December</option>
</select>
Year :
<?php
$currently_selected = date('Y');
$earliest_year = 1950;
$latest_year = date('Y');
print '<select name="year">';
foreach ( range( $latest_year, $earliest_year ) as $i ) {
print '<option value="'.$i.'"'.($i === $currently_selected ? ' selected="selected"' : '').'>'.$i.'</option>';
}
print '</select>';
?>
I have only one column in the database for the date of birth.
I want to add the date, month and year together, which should result in the following: date/month/year.
How could I accomplish this?
if(isset($_POST['submit'])){
$name = trim($_POST['username']);
$date = $_POST['date'];
$month = $_POST['month'];
$year = $_POST['year'];
if($name == ''){
$error = "Add Name";
}
$DateOfBirth = $date.'/'$month;
if(!$error){
echo $DateOfBirth;
}
}
Assuming your date of birth field is a MySQL DATE field, you need to make sure that you are creating a date in the correct format i.e. YYYY-MM-DD. You can do that by using strtotime to convert your input data into a timestamp, and then date to convert that into the appropriate format:
$DateOfBirth = date('Y-m-d', strtotime("$date $month $year"));
For example:
$year = 2015;
$month = 'August';
$date = 5;
$DateOfBirth = date('Y-m-d', strtotime("$date $month $year"));
echo $DateOfBirth;
Output:
2015-08-05
Demo on 3v4l.org
Note
If you really want the result to be in dd/mm/yyyy format, just change the first input to date to 'd/m/Y'.
The reason is your are not concatenating the variables in php. Check below code. You are almost there but with small coding mistake.
What you are trying to do is concatenate a variable with a string. So you have to concatenate variable with a '.' and then add your string. In here / works as the string. When adding a string it should be with in quotations '/' . And the final output will be something like this. $variable . '/'. Now concatenate another variable. Then it would be like this. $variable01 . '/' . $variable02.
$DateOfBirth = $date.'/'.$month.'/'.$date ;
Output
12/02/2020
Check the added example with respect to your requirement
example

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.

Calculate age in php

Hey guys I am working on my colleague project and he used below code to store age from database and shows age in view
He select date and month from select tag.
view BOD select tag image
<?php $today = date("Y");
$year = $today - 18;?>
<select class="form-control" id="date" name="day" >
<option label=01 value=01>01</option>
<option label=02 value=02>02</option>
<option>.......</option>
<option label=30 value=30>30</option>
<option label=31 value=31>31</option>
</select>
<select class="form-control" id="month" name="month" >
January
<option label=January value=01>January</option>
February
<option label=February value=02>February</option>
<option>.......</option>
November
<option label=November value=11>November</option>
December
<option label=December value=12>December</option>
</select>
<select class="form-control" id="year" name="year" >
<?php for($i = 0; $i <= 75; $i++):?>
<option value=<?=$year?>><?=$year?></option>
<?php echo $year = $year -1 ;?>
<?php endfor;?>
</select>
result image
controller
public function user_register()
{
$data = array(
'u_day'=>$this->input->post('day'),
'month'=>$this->input->post('month'),
'year'=>$this->input->post('year'),
'age'=>$this->getAge($this->input->post('year')),
);
$id = $this->admin_model->insertData('users',$data);
$sess = array(
'userid'=>$id,
'fname'=>$this->input->post('first_name'),
'mname'=>$this->input->post('middle_name'),
'lname'=>$this->input->post('last_name'),
'gender'=>$this->input->post('gender'),
'reg'=>'1',
);
$this->session->set_userdata($sess);
redirect($this->config->item('base_url').'profile/basic_details');
}
public function getAge($then) {
$then_ts = strtotime($then);
$then_year = date('Y', $then_ts);
$age = date('Y') - $then_year;
if(strtotime('+' . $age . ' years', $then_ts) > time()) $age--;
//print_r($age);exit;
return $age;
}
It works perfectly when I select any other date.
but when I select (01/01/2000) date it store age in database as -1
Generate the birth date by concatenating the strings.
$date1 = date_create("2013-03-15"); // generate this by "$date-$month-$year"; // your case
$date2 = date("Y-m-d"); // get today's date
$diff = date_diff($date1,$date2); //here you get the difference
You can apply mathematical operations to get exact exact years and months.
**Php Version >= 5.3**
# **get date and change date formate**
$from = new DateTime('1970-02-01');
$to = new DateTime('today');
echo $from->diff($to)->y;
echo date_diff(date_create('1970-02-01'), date_create('today'))->y;
**Mysql Version >= 5.0**
SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age
I can not see any code in the question that attempts to calculate the age of a user as suggested by the title of the question - consequently can not suggest how to edit the code appropriately. However, as I mentioned in my comment and has been used elsewhere in answers by #Danyal & #Anil, it would be easier and more reliable to use the DateTime class with it's associated methods.
The code below is just a quick rewrite of the question to make it viable and enable the demo to work. The code that processes the user selection is within the if code block below and should be well commented.
$today = date( 'Y' );
$year = $today - 18;
$maxyears = 120;
$html=array();
$html[]='<form method="post">';
/* days */
$html[]='<select class="form-control" name="day">';
for( $i=1; $i <= 31; $i++ )$html[]=sprintf('<option value=%d>%d',$i,$i);
$html[]='</select>';
/* months */
$html[]='<select class="form-control" name="month">';
for( $i=1; $i <= 12; $i++ )$html[]=sprintf('<option value=%d>%s', $i, date('F',mktime( 0, 0, 0, $i ) ) );
$html[]='</select>';
/* years */
$html[]='<select class="form-control" name="year">';
for( $i=$year; $i >= ( $today - $maxyears); $i-- )$html[]=sprintf('<option value=%d>%d',$i,$i);
$html[]='</select>';
$html[]='<input type="submit" />';
$html[]='</form>';
/* output menus */
echo implode( PHP_EOL, $html );
/***** Process Form submission and calculate Age *****/
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['day'], $_POST['month'], $_POST['year'] ) ){
/* Establish rules for filtering POSTED data */
$args=array(
'day' => FILTER_SANITIZE_NUMBER_INT,
'month' => FILTER_SANITIZE_NUMBER_INT,
'year' => FILTER_SANITIZE_NUMBER_INT
);
/* Filter POST data */
$_POST=filter_input_array( INPUT_POST, $args );
/* Extract data to variables */
extract( $_POST );
/* create a new date using supplied POST data - using `mktime` to generate a valid timestamp */
$date = date( 'Y-m-d', mktime( 0, 0, 0, $month, $day, $year ) );
/* create DateTime objects and calculate age ( date difference ) */
$now = new DateTime();
$dob = new DateTime( $date );
/* use the `diff` method to find the difference between two dates */
$diff = $now->diff( $dob );
/*
show the age
use the `$diff->format('%y')` method or the shorthand method `$diff->y`
*/
printf('Age: %d', $diff->y ); #same as $diff->format('%y');
Looking at the getAge function produced very odd results - so I tweaked it and arrived at the following - seems to more or less do what is needed.
function getAge( $date ) {
$now = date( 'Y' );
$diff = $now - $date;
if( strtotime( '+' . $diff . ' years', strtotime( $date ) ) < time() ) $diff--;
return $diff;
}
echo getAge( 2017 ); // -> 1
echo getAge( 2000 ); // -> 18

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'];

Categories