Managing <DateTime-local> input type with max min and default value
datetime-local input uses RFC 3339 format for input and output. User input of date and time can be collected by using this input type.
We will develop sample codes to collect the data and how to set the default values along with data for max , min attributes.
Creating the date and time object using datetime-local as input
As we receive the input as POST ( or GET ) method, the PHP code part is here to create the date and time object.
//$dt=$_POST['dt']; // Getting data from POST method of form
$dt="2019-02-16T16:56:49";
$date = DateTime::createFromFormat('Y-m-d\TH:i:s', $dt);
if($date){$msg=' Date object is created using the input ';}
else{$msg=' Unable to create date object ';}
echo $msg;
Setting present date and time as default value for datetime-local input
$date = new DateTime(); // Date object using current date and time
$dt= $date->format('Y-m-d\TH:i:s');
echo "<input type='datetime-local' id='input_time' name='input_time' value='$dt'>";
Output is here :
datetime-local with Maximum Minimum and default value setting
$dt_min = date_create('2018-12-31 23:15:40'); // Minimum limit
$dt_min= $dt_min->format('Y-m-d\TH:i:s');
$dt_max = date_create('2015-05-31 20:14:45'); // Maximum limit
$dt_max= $dt_max->format('Y-m-d\TH:i:s');
$dt = new DateTime(); // Date object using current date and time
$dt= $dt->format('Y-m-d\TH:i:s');
echo "<input type='datetime-local' id='input_time' name='input_time' value='$dt' min='$dt_min' max='$dt_max'>";
Output is here
With Maximum and minimum period from current date and time
Minimum allowed date is previous one month 10 days and Maximum allowed date is one month and 10 days from todays
$dt_min = new DateTime('-1 month -10 days');
$dt_min= $dt_min->format('Y-m-d\TH:i:s');
$dt_max = new DateTime('+1 month 10 days'); // Maximum limit
$dt_max= $dt_max->format('Y-m-d\TH:i:s');
$dt = new DateTime(); // Date object using current date and time
$dt= $dt->format('Y-m-d\TH:i:s');
echo "<input type='datetime-local' id='input_time' name='input_time' value='$dt' min='$dt_min' max='$dt_max'>";