Bootstrap Datetimepicker – Add DateTime Picker to Input Field using jQuery

DateTime picker is very useful to enable input field for date and time entry. DateTime picker provides a user-friendly way to select date and time. The user can select date and time from the DateTime picker dialog without typing manually in the input field. If your web application uses Bootstrap framework, you can easily add DateTime picker to input field using Bootstrap DateTime Picker jQuery plugin.

The bootstrap DateTimePicker plugin helps to add DateTime picker in the input element of the form using jQuery. It provides an instant solution to add datetimepicker popup in a form field for selecting date and time in the website. You can allow the user to select day, month, year, hour, and minute with one click from DateTime picker dropdown. In this tutorial, we will show you how to add a datetimepicker in the form field to select date and time in Bootstrap.

Bootstrap Library

To use the Bootstrap framework in the website, include the Bootstrap and jQuery library files.

<!-- jQuery library -->
<script src="js/jquery.min.js"></script>

<!-- Bootstrap library -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="bootstrap/js/bootstrap.min.js"></script>

Bootstrap DateTime Picker

Include the CSS and JS library of the Bootstrap Datetimepicker plugin.

<link href="css/bootstrap-datetimepicker.css" rel="stylesheet">
<script src="js/bootstrap-datetimepicker.min.js"></script>

Datetime Picker

The following code snippet adds datetimepicker to pick the date & time.

Define an HTML element to add DateTime picker.

<input type="text" id="datetime" readonly>

Call datetimepicker() method to initialize DateTime Picker plugin.

<script>
    $("#datetime").datetimepicker({
        format: 'yyyy-mm-dd hh:ii'
    });
</script>

Add Date-Time Picker to Input Field using jQuery

The DateTime picker provides various options to customize the DateTimePicker box. The following examples are some of the advanced configurations for DateTime Picker dialog box.

Inline Datetime Picker

The following code snippet adds datetimepicker to an inline DIV element.

<div id="datetime"></div>
<script>
    $("#datetime").datetimepicker();
</script>

Datetime Picker with Auto Close

Once the user selects a date & time, the datetimepicker will be closed automatically.

<input type="text" id="datetime" readonly>
<script>
    $("#datetime").datetimepicker({
        format: 'yyyy-mm-dd hh:ii',
        autoclose: true
    });
</script>

Datetime Picker with Today Link

The Today link will appear under the datetimepicker to select current date and time.

<input type="text" id="datetime" readonly>
<script>
    $("#datetime").datetimepicker({
        format: 'yyyy-mm-dd hh:ii',
        autoclose: true,
        todayBtn: true
    });
</script>

Disable Previous Dates from Datetime Picker

Use the startDate option and specify a current date to disable past dates.

<input type="text" id="datetime" readonly>
<script>
    var today = new Date();
    $("#datetime").datetimepicker({
        format: 'yyyy-mm-dd hh:ii',
        autoclose: true,
        todayBtn: true,
        startDate : today
    });
</script>

Datetime Picker with Date Range

Use the setStartDate and setEndDate method to select a date range (start date and end date).

<input type="text" id="from" readonly>
<label>TO</label>
<input type="text" id="to" readonly>
<script>
    var today = new Date();
    $('#from').datetimepicker({
        format: 'yyyy-mm-dd hh:ii',
        autoclose: true,
        todayBtn: true,
        startDate : today
    }).on('changeDate', function(ev){
        $('#to').datetimepicker('setStartDate', ev.date);
    });
    
    $('#to').datetimepicker({
        format: 'yyyy-mm-dd hh:ii',
        autoclose: true,
        todayBtn: true,
        startDate : today
    }).on('changeDate', function(ev){
        $('#from').datetimepicker('setEndDate', ev.date);
    });
</script>

DateTimePicker with Date Picker Only

The following code snippet displays only date picker to select date only.

<input type="text" id="date" readonly>
<script>
    $('#date').datetimepicker({
        format: 'yyyy-mm-dd',
        weekStart: 1,
        todayBtn:  true,
        autoclose: true,
        todayHighlight: true,
        startView: 2,
        minView: 2,
        forceParse: 0
    });
</script>

DateTimePicker with Time Picker Only

The following code snippet displays only time picker to select time only.

<input type="text" id="time" readonly>
<script>
    $('#time').datetimepicker({
        format: 'hh:ii',
        weekStart: 1,
        todayBtn:  true,
        autoclose: true,
        todayHighlight: true,
        startView: 1,
        minView: 0,
        maxView: 1,
        forceParse: 0
    });
</script>

Submit and Insert DateTime Field Value into the Database

Now, we will show you how to submit the datetime form field and insert as DATETIME format into the database using PHP and MySQL. For the better understanding, we’ll build an example PHP script that submits the event name and date & time into the MySQL database.

Create Database Table:
A table needs to be created in the database to store the event name and datetime. The following SQL creates a events table in the MySQL database.

CREATE TABLE `events` (
 `id` int(22) NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `datetime` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

HTML Code:
The following HTML contains two form fields, one for text input (event name) and another for datetime input (event date & time).

<form method="post">
    Event: <input type="text" name="name" class="form-control">
    Date & Time: <input type="text" name="datetime" id="datetime" class="form-control" readonly>
    <input type="submit" name="submit" class="btn button btn-success" value="SUBMIT" />
</form>

JavaScript Code:
Specify the element selector (#datetime) to attach datetime picker to the datetime input field. The previous dates will be disabled for preventing user select a past date.

<script>
    $(function () {
        var today = new Date();
        var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
        var time = today.getHours() + ":" + today.getMinutes();
        var dateTime = date+' '+time;
        $("#datetime").datetimepicker({
            format: 'yyyy-mm-dd hh:ii',
            autoclose: true,
            todayBtn: true,
            startDate: dateTime
        });
    });
</script>

PHP Code:
Specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName) as per your MySQL database credentials. Once the form is submitted, the event name and event date & time will be inserted into the database using PHP and MySQL.

<?php
if(isset($_POST['submit']) && !empty($_POST['name']) && !empty($_POST['datetime'])){
    
// Database configuration
    
$dbHost        'localhost';
    
$dbUsername    'root';
    
$dbPassword    'root';
    
$dbName        'codexworld';
    
    
// Connect and select the database
    
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);
    
    
// Check connection
    
if ($db->connect_error) {
        die(
"Connection failed: " $db->connect_error);
    }
    
    
// Get fields value
    
$name $db->real_escape_string($_POST['name']);
    
$datetime $db->real_escape_string($_POST['datetime']);
    
    
// Insert datetime into the database
    
$insert $db->query("INSERT INTO events (name, datetime) VALUES ('".$name."', '".$datetime."')");
    
    
// If insert successful
    
if($insert){
        
$status 'Event data inserted successfully. Event ID: '.$db->insert_id;
    }else{
        
$status 'Failed to insert event data.';
    }
}
?>

Conclusion

DateTimePicker helps to make datetime input field user-friendly. You can convert an input field to a DateTime picker using jQuery. Our example code allows you to add DateTime picker to input text field using Bootstrap DateTimePicker plugin. Also, you can customize the DateTimePicker with various configuration options as per your needs.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

8 Comments

  1. Akinwumi Ayotunde Said...
  2. Sadick Said...
  3. Atul Kabadi Said...
  4. Milan P Said...
  5. Js Said...
    • CodexWorld Said...
  6. Milan P Said...
    • CodexWorld Said...

Leave a reply

keyboard_double_arrow_up