Data privacy notice

 

When this content is loaded, usage information is transmitted to Vimeo and may be processed there.

 

             

datepicker (Adjust date format)

Modified on Fri, 21 Jul, 2023 at 10:24 AM

By default, the German date format is used. This section explains how you can use other date formats.

Contents



An example for using other date formats. For each input field, you can set a different date format via JavaScript. This requires that you include a language file. You also need to make sure you change the validation appropriately so that it accounts for the new date format.

The following steps are necessary, explained in detail below:

  • The user can select a date via a popup calendar. This is done with the function datepicker from the library jQueryUI: demo, docs. This library supports different date formats.
  • The global datepicker object is stored in jQuery.datepicker. It contains some utility functions for parsing and formatting a date, see for datepicker.formatdate.
  • Date format settings for different regions are stored in $.datepicker.regional, such as $.datepicker.regional["fr"] for the French date format.
  • To set the default date format, you can use the function setDefault: $.datepicker.setDefault($.datepicker.regional("fr")).
  • To change the date format for a single input field, select it and call the datepicker method: $("[name='tfDateFr']").datepicker($.datepicker.regional["fr"]).
  • You also need to modify the validation process so that it accounts for the new date format. This can be achieved with the datatype regular expression, or by setting up a custom jQuery.fn.errorfunc.


Adding a date format

Existing language

A language file containing the date format for a different region. You should delete the highlighted line in the language file. We will set the language to be used later in the form.

By default, the calendar ships with support for the two languages English and German, with German being the default. To support more languages or regions, you need to add the corresponding language file to the form:

You can download language files for many languages from the jQuery UI pages.

For each language file you download, you should make a small edit: Delete the following line at the end of the language file:

datepicker.setDefaults( datepicker.regional.xx );

Now you can upload the lanugage files, either 

  • as a form file when you only need them for a single form, or
  • as a client file to make it available for all forms.


Own date format

If necessary, you can create and add your own custom date format. The easiest way to do so is to take an existing language files and edit it. You need to add an entry to the list of the date format in $.datepicker.regional. This entry must be an object with the options for the date format. It may contain the following entries:

closeText, prevText, nextText,
currentText, monthNames, monthNamesShort,
dayNames, dayNamesShort, dayNamesMin,
weekHeader, dateFormat, firstDay,
isRTL, showMonthAfterYear, yearSuffix

See the documentation for more information on these options.


Changing the date format

Once you added the language files, you can now change the date format for the form. You have two options: change the default date format or specify a different date format only for a certain input field. After you did that, you should also make sure the date format gets validated correctly, see below.


Global date format

In case you would like to change the date format for all input fields, you can set the default language. Create a new JavaScript file and name it, for example, datepicker-locale.js. Upload this file as a client or form file, depending on whether you want the changes to apply to all forms or only a specific form. 

Users may open the form in different languages. To set the date format depending on the current language, add the following code to the JavaScript file:

$(() => {
    // Get the date format for the current language
    const locale = $.datepicker.regional[XFC_METADATA.currentLanguageTag];
    // Set it as the default date format
    // If no such date format was found, fall back to English
    $.datepicker.setDefaults(locale || $.datepicker.regional["en"]);
});

$(function() {
    // Get the date format for the current language
    var locale = $.datepicker.regional[XFC_METADATA.currentLanguageTag];
    // Set it as the default date format
    // If no such date format was found, fall back to English
    $.datepicker.setDefaults(locale || $.datepicker.regional["en"]);
});

The code above changes the default date format for all those input fields for which the datatype was set to date. Now users may open the form as follows:

# In French
https://formcycle.eu/formcycle/form/provide/2152?lang=fr

# In Dutch
https://formcycle.eu/formcycle/form/provide/2152?lang=nl


Specific input field

In case you only wish to change the date format for a single input field, go to the JavaScript tab. Select the input field with jQuery and call the datepicker method from jQuery UI:

// Select the input field named "tfDateFr"
const tfDateFr = $("[name='tfDateFr']");

// Remove the current calendar
tfDateFr.datepicker("destroy");

// Activate calendar with French date format
tfDateFr.datepicker($.datepicker.regional.fr);
// Select the input field named "tfDateFr"
var tfDateFr = $("[name='tfDateFr']");

// Remove the current calendar
tfDateFr.datepicker("destroy");

// Activate calendar with French date format
tfDateFr.datepicker($.datepicker.regional["fr"]);

Validating the date format

Users may not use the calendar and enter the date directly, so you should validate the input and whether it represents a valid date according to the date format. By default, the validation process only checks for the German date format. To change it, there are two options.


Via a custom error function

When you use a custom error function, do not activate the option to validate the data on the server. It will not know about the JavaScript logic you added.


Use this method if you only changed the default date format. Add a custom jQuery.fn.errorfunc to the date input fields. The following code can be added to the file datepicker-locale.js mentioned above:

$(() => {
    /**
     * @param {JQuery} input
     */
    function checkDate(input) {
        const dateFormat = input.datepicker("option", "dateFormat");
        const settings = input.data("datepicker").settings;
        const value = input.val();
        try {
           const date = $.datepicker.parseDate(dateFormat, value, settings);
           return "";
        }
        catch (e) {
            return XM_FORM_I18N.dateIntl || XM_FORM_I18N.dateDE;
        }
    }

    $(".XTextField.hasDatepicker").each((_, el) => $(el).errorFunc(function() {
      return checkDate($(this));
    }));
});
$(function() {
    function checkDate(input) {
        var dateFormat = input.datepicker("option", "dateFormat");
        var settings = input.data("datepicker").settings;
        var value = input.val();
        try {
           var date = $.datepicker.parseDate(dateFormat, value, settings);
           return "";
        }
        catch (e) {
            return XM_FORM_I18N.dateIntl || XM_FORM_I18N.dateDE;
        }
    }

    $(".XTextField.hasDatepicker").each(function(_, el) {
      $(el).errorFunc(function() {
        return checkDate($(this));
      });
    });
});

This code checks whether the entered date is valid, according to the current date format of the date input field. In case the entered date is invalid, show the error message from the i18n variable dateIntl. This i18n variable can be created or edited in the backend configuration. You can use a different error message for each language.


Via a regexp

Use this method in case you only changes the date format for a specific input field. Go to the constraints sections of the properties panel of the formcycle Designer and select the datatype regular expression. To get the calendar to show up, you need to call the method $.fn.datepicker manually (this is also where you can specify the date format to be used). Now you can enter the regexp to validate the date format, and also enter a custom error message. For a french date:

^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$


Additional script functions

The datepicker of the library jQuery UI offers some additional utility methods for working with dates, see also documentation. Here are some often used functions.


Read and set the date

The text in the date input field is the formatted date and can be read via the jQuery function $.fn.val. If you need the date as a (parsed) date object for other custom JavaScript logic, you can read it via the method getDate, or set it  with the method setDate.

// Read the formatted value
// "05.01.2017"
$("[name=tfDate]").val();

// Read the date as a date object
// "2017-01-04T23:00:00.000Z"
$("[name=tfDate]").datepicker("getDate").toISOString();

// Set the date to the 22nd of May, 1990
$("[name=tfDate]").datepicker("setDate", new Date(1990,4,22));


Server date

To access the current date of the server, independent of the browser, use XFC_METADATA.serverdate. You could also prefill a date input field with the current date:

// Write the current date to the input field named "tfDate"
$("[name=tfDate]").datepicker("setDate", XFC_METADATA.serverTime);


Format date

Use the utility function from jQuery UI to format a date according to a given date format:

$.datepicker.formatDate( format, date, options );

For the third optional argument (the options) you can use one of the date format entries in $.datepicker.regional. The first argument is a format string that may contain the following patterns:

PatternExplanation
dDay of the month, without a leading zero
ddDay of the month, with a leading zero (two digits)
oDay of the year, without a leading zero
ooDay of the year, with a leading zero (three digits)
DShort day name, eg. Mon or Wed
DDLong day name, eg. Monday or Wednesday
mMonth, without a leading zero
mmMonth, with a leading zero (two digits)
MShort month name, eg. Jun. or Dec.
MMLong month name, eg. June or December
yYear, two digits
yyYear, four digits
@Unix time (milliseconds since 01.01.1970)
!Windows time (Time since 01.01.0001, in units of 100ns


For example:

// "16.01.2017 (Monday)"
$.datepicker.formatDate("dd.mm.yy (DD)", XFC_METADATA.serverTime);

// "17/1/5"
$.datepicker.formatDate("y/m/d", XFC_METADATA.serverTime);

// "16-01-2017 (Monday)"
$.datepicker.formatDate("dd-mm-yy (DD)", XFC_METADATA.serverTime);

// Force french date format
// "16-01-2017 (janvier[janv.]-lundi[lun.])"
$.datepicker.formatDate("dd-mm-yy (MM[M]-DD[D])", new Date(), {
  dayNamesShort: $.datepicker.regional[ "fr" ].dayNamesShort,
  dayNames: $.datepicker.regional[ "fr" ].dayNames,
  monthNamesShort: $.datepicker.regional[ "fr" ].monthNamesShort,
  monthNames: $.datepicker.regional[ "fr" ].monthNames
});


Parse date

Similar to how you can format a date, you can also parse a string as a date:

$.datepicker.parseDate(format, value, options )

The first and third argument work the same way as with the function for formatting a date. For example:

// Read the date "05-Januar-2017"
$.datepicker.parseDate("dd-MM-yy", "05-Januar-2017", {
  monthNames: $.datepicker.regional["de"].monthNames,
});

// Read the date "05-Janvier-2017"
$.datepicker.parseDate("dd-MM-yy", "05-Janvier-2017", {
  monthNames: $.datepicker.regional["fr"].monthNames,
});

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article