48

I'm working on some internationalization using jQueryUI. I have a DatePicker control on a form that is properly working in the French language.

When I select a date, for example August 15, 2012, the DatePicker will display 15 Aoû, 2012 as I would expect. My issue however, is that when the form is posted, the value of the DatePicker is posted as '15 Aoû, 2012' which now needs to be translated on the server before it can be saved properly.

My question is, is there a built-in way inside the jQueryUI DatePicker so that I can have it always post to the server in a consistent format, regardless of which language the control is being displayed in? If there isn't a built-in way, what options exist for achieving this?

I realize that I can change the dateformat to something like 08/15/2012 instead of using the textual representation, however this isn't what I want to do.

Wally Lawless
  • 7,539
  • 7
  • 37
  • 53

7 Answers7

51

There's 2 configuration options for that: altField and altFormat. http://api.jqueryui.com/datepicker/#option-altField If you specify an altField, that field will be updated too, and will have the altFormat. Normally you will want make the altField a hidden field, soyou can ignore the regular field and send to db the altField.

iwiznia
  • 1,669
  • 14
  • 21
10

As you'll have noticed, supplying a dateFormat works well for newly entered dates, but it does not alter the value attribute which was already supplied to the date input field. It took me some time and I'm not sure whether this solution is ideal, but here's my situation explained and the code which solves it. Might help others with the same problem in the future. In my example I'm using dd/MM/yyyy as the display format.

  1. The page contains any number of date input fields, which may or may not already have a value attribute supplied in the format yyyy-MM-dd, as specified by W3C.
  2. Some browsers will have their own input control to handle dates. At the time of writing, that is for instance Opera and Chrome. These should expect and store a date in the abovementioned format, while rendering them according to the client's regional settings. You probably do not want/need to create a jqueryui datepicker in these browsers.
  3. Browsers which don't have a built-in control to handle date input fields will need the jqueryui datepicker along with an 'alt', invisible field.
  4. The invisible, alt input field with the yyyy-MM-dd format must have the original name and a unique id in order for forms logic to keep working.
  5. Finally, the yyyy-MM-dd value of the display input field must be parsed and replaced with its desired counterpart.

So, here's the code, using Modernizr to detect whether or not the client is able to natively render date input fields.

if (!Modernizr.inputtypes.date) {
    $('input[type=date]').each(function (index, element) {
        /* Create a hidden clone, which will contain the actual value */
        var clone = $(this).clone();
        clone.insertAfter(this);
        clone.hide();

        /* Rename the original field, used to contain the display value */
        $(this).attr('id', $(this).attr('id') + '-display');
        $(this).attr('name', $(this).attr('name') + '-display');

        /* Create the datepicker with the desired display format and alt field */
        $(this).datepicker({ dateFormat: "dd/mm/yy", altField: "#" + clone.attr("id"), altFormat: "yy-mm-dd" });

        /* Finally, parse the value and change it to the display format */
        if ($(this).attr('value')) {
            var date = $.datepicker.parseDate("yy-mm-dd", $(this).attr('value'));
            $(this).attr('value', $.datepicker.formatDate("dd/mm/yy", date));
        }
    });
}
Vincent Sels
  • 2,711
  • 1
  • 24
  • 31
  • 1
    NB: If you use the on keydown/keyup event to init the datepicker (useful if you want datepicker on dynamically created elements), be aware to add this code to not recreate the input at each click: `var inputId = $(this).attr('id'); if (inputId.indexOf('-display') !== -1) { return }` – Guicara Oct 25 '16 at 12:34
0
<input type="text" name='fieldName' id="datepicker" value="" style="width: 100px;" />
<script type="text/javascript">
    $( "#datepicker" ).datepicker( "option", "dateFormat", 'dd/mm/yy' );
    $( "#datepicker" ).datepicker();
</script>
Nish
  • 2,296
  • 2
  • 14
  • 19
0

It appears someone else had this question or a similar one prior to yours.

If you read this stackoverflow answer, the author was trying to show the date in one format and pass the data to MySQL in another format.

The prior answer in that link gets you set up to access the selected value as a variable. Now all you need is to wire in a parseDate to your selected date variable.

<script type="text/javascript">
    $('#cal').datepicker({
             dateFormat: 'dd M yy',
             onSelect: function(dateText, inst) { 
             var dateAsString = dateText; //the first parameter of this function
             var newDateFormat = $.datepicker.parseDate('dd-mm-yyyy', dateAsString);
           }
    });
</script>

Check the parseDate link for settings and formatting.

Hope this helps!

Community
  • 1
  • 1
Bechard
  • 1
  • 2
  • Wally, this example allows for your display format in dd M yy, while passing the selected data as dd-mm-yyyy. Adjust the output format for your needs. – Bechard Jul 17 '12 at 13:06
  • I really don't understand this answer. Please explain how you can use this method to pass the date to the database in a chosen format different from the displayed format. – Vincent Jan 22 '20 at 18:42
  • You should probably try an answer that isn't from 2012, as this probably isn't relevant after eight years of changes to jQuery. Best of luck! – Bechard Mar 05 '20 at 20:22
  • The correct way to use `onSelect` for setting another date format for display is explained in [this answer](https://stackoverflow.com/a/8672511/3002584). – OfirD May 04 '21 at 12:11
0

Basically, you should not re-format the date. Instead, you should read JavaScript's Date object from Datepicker, via getDate() method. Then, you need to pass it to server.
The question is how. Basically, what you want is some common format. If you use JSON the answer is very simple, just put date object and JSON's stringify() function will automatically format it to ISO8601.

As you may see from Wikipedia, ISO8601 was designed to interchange date and time reliably, therefore that's what you should use.
It might be helpful to know that modern web browsers support Date object's toISOString() method.

Paweł Dyda
  • 18,366
  • 7
  • 57
  • 79
0

As @Pawel-Dyda mentioned, There's a

getDate() method

var currentDate = $( ".selector" ).datepicker( "getDate" );

Here's an example of what it returns: Wed Jan 20 2016 00:00:00 GMT+0300.

You can parse it in Javascript, PHP, in SQL or whatever.


MySQL parsing examlple:

select str_to_date('Wed Jan 20 2016 00:00:00 GMT+0300','%a %b %d %Y %H:%i:%s');

Returns:

2016-01-20 00:00:00
NikitOn
  • 448
  • 4
  • 10
0

Solution working for ASP.NET

@using (Html.BeginForm("ActionName", "ControllerName"))
{
    @Html.HiddenFor(m => m.DateFrom)
    @Html.HiddenFor(m => m.DateTo)

    <div class="form-group">
        @Html.LabelFor(m => m.DateFrom)
        <input id="datepicker-date-from" type="text" class="form-control datepicker" value="@Model.DateFrom.Date.ToString("dd.MM.yyyy")"/>
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.DateTo)
        <input id="datepicker-date-to" type="text" class="form-control datepicker" value="@Model.DateTo.Date.ToString("dd.MM.yyyy")" />
    </div>

    <input type="submit" class="btn btn-sn btn-primary" value="Download" />
}


@section scripts {
    <script type="text/javascript">

        $(function () {
            $("#datepicker-date-from").datepicker(
            {
                dateFormat: "dd.mm.yy",
                altField: @Html.IdFor(m => m.DateFrom),
                altFormat: "yy-mm-dd"
            });

            $("#datepicker-date-to").datepicker(
            {
                dateFormat: "dd.mm.yy",
                altField: @Html.IdFor(m => m.DateTo),
                altFormat: "yy-mm-dd"
            });
        });

    </script>
}
Muflix
  • 6,192
  • 17
  • 77
  • 153