Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap date time picker display format vs value format

I am using the following plugin for selecting date and time.

https://eonasdan.github.io/bootstrap-datetimepicker/

It works great in most cases. However in some cases I display the date in the input field as MM/DD/YYYY but when I submit to server, I need it as YYYY-MM-DD

What is the best way to accomplish this? I am thinking of overriding submit function for the form. But I kind of want to avoid this as I would like to somehow do it all using their events so I can contain the code in one place instead of adding a bunch of logic for each form.

like image 488
Chris Muench Avatar asked Jul 20 '15 23:07

Chris Muench


People also ask

What is bootstrap datepicker?

Bootstrap date picker is a plugin that adds the function of selecting time without the necessity of using custom JavaScript code. This documentation may contain syntax introduced in the MDB 4.17. 0 and can be incompatible with previous versions.

How do you use a date picker?

The datepicker is tied to a standard form input field. Focus on the input (click, or use the tab key) to open an interactive calendar in a small overlay. Choose a date, click elsewhere on the page (blur the input), or hit the Esc key to close. If a date is chosen, feedback is shown as the input's value.


1 Answers

Ashish and Chris code may work, but since Bootstrap 3 Datepicker requires Moment.js, why not use Moment.js Parse (to parse the date from your custom or locale format chosen for the datepicker) and Moment.js Format (to convert the date in ISO format e.g. to be sent to an ASP.NET controller or other endpoints accepting that kind of format for DateTime)?

So the code would be way much shorter, like this:

  $('#datetimepicker1').on("dp.change",
    function (e) {
      var submitDateString = '';
      if (e.Date) {
        submitDateString = e.Date.format();
      }
      $("#datetime-submit").val(submitDateString);
    });

Note (see comment below): e.Date may need to be e.date to work.

Explanation:

  • the dp.change event (e) has a Date property, which is a moment object, so you don't even need to care what was the date format you chose for the datepicker.
  • when the datepicker is cleared e.Date is false, thus the if check.
  • $("#datepicker1") is the input field where I bind bootstrap datepicker.
  • $("#datetime-submit") is my hidden input field.

To answer the OP, if the desired format to submit is "YYYY-MM-DD", then use:

submitDateString = e.Date.format("YYYY-MM-DD");

I just discovered Moment.js and love it. Use it to make date parsing & displaying easier.

like image 100
firepol Avatar answered Nov 14 '22 22:11

firepol