Bootstrap DateTime Picker


Dates in Web Apps

Dates can be interesting in web applications. Being a dBASE developer I thought I had a pretty good handle on dates, datetime formats, etc. However, as it turns out, each programming language on the web and each database you might want to use on the web handle date formatting differently. Eeep!

Worse, if you want a good user front-end for your dates, you need some sort of calendar with whatever capabilities are necessary for your specific application.

I spent nearly a week looking at many different options (and there are a lot) on the web, and eventually settled on a specific control, partially because it is pretty popular, but also because it looks good and does what I need.

Bootstrap itself does not come with a date time "picker" or calendar control, so instead I found the one by Jonathan Peterson at [DateTimePicker (GitHub)]. This control requires several files, and at the end of this page I will put them into a single .zip file if you wish to download them. Note that this is free code, but should always be used under the license that comes with it. I always try to make sure I credit people where I can, you should, too. A lot of effort went into this code and the least you can do is credit the author.

One of the traps that got me was that with all the testing of different calendar controls I was doing, I ended up with multiple versions of some files, and these actually caused me a lot of heartburn.

Jonathan's code requires the following files:

Setup

To use this control, you need to insert calls to the files. I keep my Javascript files in a folder off the root level of my site called "jscode", and my CSS (Cascading Style Sheets) in a folder (also off the root) called "css".

Toward the top of your page (usually in the head section of a web site) you should have a statement like:

               <link rel="stylesheet" type="text/css" href="../css/bootstrap-datetimepicker.css" />
            

Toward the bottom of the page, you should have these lines to include the javascript code necessary for this control to work:

               <!-- datetime picker -->
               <script type="text/javascript" src="jscode/moment.js"></script>
               <script type="text/javascript" src="jscode/bootstrap-datetimepicker.js"></script>
            

It is important to note that the "moment.js" statement comes before the other, sequence is important for your Javascript code.

From there you need to put together an HTML input control that is set up to handle dates. Using my CMS as an example, in the "Events" form used to add/edit events on the site, I pull data from the table (if I'm editing) or set the values otherwise in some fashion. then I use the following to lay out the page:

               <div class="row">
                  <div class="col-md-6">
                     <label for="event_start">Event Starts:</label>
                        <div class="input-group date" id="datetimepicker1" style="width: 250px;">
                           <input name="event_start" id="event_start" type="text"
                                 class="form-control"
                                 required
                                 value = "" />
                           <span class="input-group-addon">
                              <span class="glyphicon glyphicon-calendar"></span>
                           </span>
                        </div>
                     <p class="help-block">Provide the starting date and time (Required).</p>
                  </div> <!-- / first column -->
               
                  <div class="col-md-6">
                     <label for="event_end">Event Ends:</label>
                        <div class="input-group date" id="datetimepicker2" style="width: 250px;">
                           <input name="event_end" id="event_start" type="text"
                              class="form-control"
                              value = "" />
                           <span class="input-group-addon">
                                 <span class="glyphicon glyphicon-calendar"></span>
                           </span>
                        </div>
                     <p class="help-block">Provide the ending date and time if relevant.</p>
                  </div> <!-- end second column -->
               </div> <!-- / row -->
            

The code above will give (I put this in a Bootstrap "well" to make it stand out from the rest of the page, normally it would appear with the background of your page, etc.):

Provide the starting date and time (Required).

Provide the ending date and time if relevant.

All of the above looks good, but does not do something we need -- we need some specific Javascript code that will tell the controls how to handle the dates and times ...

Under the statements provided earlier to include the .js files, add the following:

               <script type="text/javascript">
                  $(function ()
                  {
                      $('#datetimepicker1').datetimepicker(
                     {
                        locale: "en",
                        showClear: true
                     });
                  });
                  $(function ()
                  {
                      $('#datetimepicker2').datetimepicker(
                     {
                        locale: "en",
                        showClear: true
                     });
                  });
               </script>
            

There are a lot of options. The first thing to note is that each of these controls has to have a unique id, and there is a separate function for each, looking for the input tag by the the id attribute.

If you go out to the GitHub site that contains the current version of this control, you will see some documentation. It doesn't explain things really well, but you can work out a bunch of stuff.

In this particular example I am using a datetime field from MySQL for the data, and so setting the "locale" property to "en" as shown in the Javascript above, the date is formatted in US date format: 11/30/2016 11:08 AM -- month/day/year, hours/minutes and the AM/PM indicator for 12 hour time. If you're an American this format is perfect, most people can deal with it.

If you click the calendar button, a calendar appears, automatically filling in the current date and time. At the bottom of the calendar are two buttons you can click: one allows you to select the time; the other allows you to clear out the entryfield. That is what the "showClear" option is used for in the Javascript above. If that is missing then trashcan icon does not display.

I find the control easy to use. It's pretty intuitive from the end-user point of view.

Options:

For one part of my CMS I don't need the time and am just using the date. So I don't always want the full date and time to appear, and I don't need the time option on the calendar itself.

This version uses just the date:

Provide date you want this announcement to start appearing on the home page (Required).

The Javascript for that looks like:

               $(function ()
               {
                   $('#datetimepicker3').datetimepicker(
                  {
                     locale: "en",
                     showClear: true,
                     format: 'MMMM D, YYYY'
                  });
               });
            

Note the "format:" statement. This allows us to use a format as defined in the documentation for the datetime picker control, in this case, the date might appear as: November 30, 2016. If you click the calendar button note that no time appears, and the clock image does not appear.

The basic documentation is shown here, although you really have to spend some time looking through things to figure some of it out. For my needs, I have what is necessary. [Bootstrap 3 Datepicker Documentation].

Date Formats

One of the more ... shall we say "fun"? ... aspects of working with dates was mentioned earlier -- different programming languages and different databases handle dates differently.

Most of my web code to handle interacting with databases and the server is PHP. I have a small amount of experience with JSNode, and such, but I didn't like it. The database I am working with the most is MSSQL. So, the fun part is getting the data to and from the database.

To handle dates I created a set of functions in PHP that allow me to read data out of a table into PHP date format, and then back from PHP format to MySQL.

Dates from MySQL to PHP

To handle getting dates FROM MySQL, I created a function that is pretty simple. You have to pass the function the value from the date field, and what is returned is a PHP version of a date.

The fun part from there is that the date is not that useful, it's not as easily read by a human as you might like. So you might then want to use the PHP date function to convert it to something more useful. For example, we might want a date to appear as: November 30, 2016. The following two functions accomplish the task.

               function MySQL2PHP( $SQLDate )
               {
                  return strtotime( $SQLDate ) ;
               } // eof: MySQL2PHP()
               
               function PHPDate2MDY( $PHPDate )
               {
                  // convert to character string
                  return date( "F j, Y",  $PHPDate  );
               } // eof: PHPDate2MDY()
            

To use these two functions, we might need to do something like:

               // Assume we have a $row variable that points to the
               // row in the table:
               $start = MySQL2PHP( $row['startdate'] );
               $start = PHPDate2MDY( $start );
               echo $start . "<br />";
            

DateTime:
DateTime can be a bit more complex. Let's assume you want a format using the American "short" date format of "mm/dd/yyyy" followed by the time, and we want to use 12 hour time, so need the AM/PM indicator. A function like the following (which combines a call to MySQL2PHP() so you don't have to remember) would do the trick:

               function MySQL2DateTime( $SQLDate )
               {
                  $PHPDate = MySQL2PHP( $SQLDate );
                  return date( "n/j/Y g:i A", $PHPDate );
               } // eof: MySQL2DateTime()
            

Of course, then after we have worked with the dates, we would need to be able to put them back into the MySQL table.

Dates from PHP to MySQL

Returning the data to the table takes a bit of work as well.

               function PHP2MySQLDateTime( $PHPDate )
               {
                  return date( "Y-m-d H:i:s", strtotime(  $PHPDate  ) );
               } // eof: PHP2MySQLDateTime()
            
               function PHP2MySQLDate( $PHPDate )
               {
                  // convert back to SQL date for MySQL data:
                  $Temp = strtotime( $PHPDate );
                  return date( 'Y-m-d', $Temp );
               } // eof: PHP2MySQL()
            

An example for a date-only conversion would be:

               // date only:
               $start = $_POST['start']; // get data from user input
               $start = PHP2MySQLDate( $start ); // convert data to MySQL Date
            

From there you would write the data back to the table either with an UPDATE command or an INSERT INTO command as needed.

Using These Dates with the DateTime Picker

In your PHP code you would need to read the data and convert it as shown above. Then, because PHP is really pretty cool, in the HTML used to define the control, you can reference the variable you stored the date in and assign it to the value attribute:

               <div class="row">
                  <div class="col-md-6">
                     <label for="event_start">Event Starts:</label>
                        <div class="input-group date" id="datetimepicker1" style="width: 250px;">
                        <input name="event_start" id="event_start" type="text"
                              class="form-control"
                              required
                              value = "<?php echo $event_start ?>" />
                              <span class="input-group-addon">
                                 <span class="glyphicon glyphicon-calendar"></span>
                              </span>
                        </div>
                     <p class="help-block">Provide the starting date and time (Required).</p>
                  </div> <!-- / first column -->
            

The Files

As promised, the files can be downloaded from here: [bootstrap-datetimepicker.zip]

To use them, follow the instructions given above. This only works with Bootstrap, so you should make sure you have your site set up properly to work with Bootstrap.

If you are interested in my date functions, I am including the function file here as a separate download. I realize not everyone is using PHP and MySQL, but if you are, you may find these handy: [dates.php]

Summary

Once I realized that a lot of my frustration with this control was coming from the fact that I had the wrong versions of some of the files I needed, and I deleted the files used, downloaded the current version (at least at the time -- I haven't spent a lot of time going out and checking to make sure I have the absolutely most curent version since I got it working -- why break something if you don't have to?), this wasn't too difficult to implement.

I haven't spent a LOT of time trying all the permutations, as I found what I wanted and decided there was no reason to go any further. That said, this control seems to be pretty flexible. I linked to the documentation earlier in the page (above the discussion of Date Formats). I suggest if what I have shown doesn't do it for you, that you take a look there.