4

I have a jQuery datepicker with format: dd-MM-yyyy.

By default the datepicker converts dates such as 1-2-3 and 1-2-99 to 01-02-2003 and 01-02-1999 respectively. However, this is only the case when you press enter or choose the date from the datepicker. I tried to auto format the field when leaving the field by using:

$j('.datepicker').live('blur', function(){
    $j(this).datepicker('setDate', $j(this).datepicker('getDate'));
});

In this case I am using the utility function setDate and getDate of the Datepicker itself. This works when you enter the date by using your keyboard and using the TAB-key for example. However, the blur trigger also activates when you try to pick the date with your mouse. Therefore you have to choose the date twice with your mouse, because the first one the blur event sets the old value back.

Is there any event I am missing I can use?

Workaround

Not very elegant but it is a partial solution:

var timeout;
$j('#geboortedatum').live('keypress', function() {
    if(timeout) {
        clearTimeout(timeout);
        timeout = null;
    }
    timeout = setTimeout(formatDate, 1000);
});

function formatDate() {
    var gebdat = $j('#geboortedatum').val();
    var dashCount = gebdat.split('-').length - 1;
    if(dashCount == 2 && gebdat.length >= 5) {
        $j('#geboortedatum').datepicker('setDate', $j('#geboortedatum').datepicker('getDate'));
    }
}
Serkan
  • 349
  • 1
  • 2
  • 7

6 Answers6

12

I just use the onClose event within datepicker istelf:

$(function(){
    var $myDate = $('#myDate');
    $myDate.datepicker({
      dateFormat: 'dd-mm-yy',
      onClose: function(dateText, inst) {
          $(this).datepicker('option', 'dateFormat', 'dd-mm-yy');                
    }
});

});​

http://jsfiddle.net/RpUSL/

Brad
  • 413
  • 6
  • 14
3

You could use the keypress event, but then you'd have to decide how much input constitutes something worth trying to auto-format.

Personally, I prefer to limit the input the textbox accepts. To that end, I'd recommend the jQuery Masked Input plugin.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • But I want to allow the user to enter the shorter notation, like 1-2-3. keypress is perhaps worth trying in combination with a check whether length >= 5 and #dashes = 2 with a delay of 1 sec. – Serkan Sep 08 '10 at 14:10
  • @Serkan - if that works for you, then great. However, such shorter notation could really just be problematic since it's entirely nonstandard and ambiguous. Think about how many problems arise just because the date `1/2/2003` means "January 2nd, 2003" in some locales and "February 1st, 2003" in others. – Matt Ball Sep 08 '10 at 14:14
  • I completely agree with that. But it's for use in an intranet-site/application and we can assume that they are all using the day-month-year notation. – Serkan Sep 08 '10 at 14:22
  • @Serkan - fair enough. Intranet apps definitely operate under different assumptions. BTW, if you're looking to implement that check "length >= 5 and #dashes = 2 with a delay of 1 sec" then I definitely recommend the [throttle/debounce plugin](http://benalman.com/projects/jquery-throttle-debounce-plugin/) for the delay. – Matt Ball Sep 08 '10 at 14:35
2

Hate to revive a dead post, but this was the first search result for "jquery datepicker autoformat"! I didn't find any nice solutions, so this is basically what I did:

jQuery('#my_selecter').datepicker().keyup(function(e){
    if(e.keyCode != '8'){
        if (e.target.value.length == 2) e.target.value = e.target.value + "/";
        if (e.target.value.length == 5) e.target.value = e.target.value + "/";
    }
})

All this does is put in the slashes, so a user can quickly type a date. It will also not fight with the delete button. Keep in mind this will only work for US locales, and ignores problems with other things (home key, tab key, etc.).

Luke The Obscure
  • 1,524
  • 2
  • 20
  • 35
1

My solution:

$('input.datepicker').datepicker({
  dateFormat: 'dd-mm-yy',
  onClose: function(dateText, inst) {
    try {
      dateText = dateText.replace(/-(19|20)?/g,'');
      dateText = dateText.replace(/\/(19|20)?/g,'');
      if (dateText) {
        dateText = dateText.substr(0,2)+'-'+dateText.substr(2,2)+'-'+dateText.substr(4,2);
        $(this).datepicker('setDate', dateText);
      }
    } catch (err) {
      alert(dateText);
    }
  }
};

accepts formats:

dd-mm-yyyy (20th or 21th century)
dd-mm-yy
ddmmyy
dd/mm/yyyy
dd/mm/yy
0

this last example was almost right, i tweaked it a bit, so it actually sets the date properly and checks for invalid dates.

$("#ClientDOB").datepicker({
  changeMonth: true,
  changeYear: true,
  dateFormat: 'dd-MM-yy',
  defaultDate: "1-January-70",
    onClose: function(dateText, inst) {
           try {
               var d = $.datepicker.parseDate('dd-mm-yy', dateText);
               $(this).datepicker('setDate',d.getDate()+'-'+monthNames[d.getMonth()]+'-'+d.getFullYear());
             } catch (err) { // what to do if it errors, just set to date 40 years ago
               d=new Date();
               $(this).datepicker('setDate',"1-January-"+(d.getFullYear()-40));
             }
      }
});
Jon Soong
  • 117
  • 5
0

Here is a simple solution (see Brad's solution for usage):

// Reformats the input when you leave the field
onClose: function (dateText, inst) {
    // Get current datepicker's options
    var format = $(this).datepicker("option", "dateFormat");
    var settings = $(this).datepicker("option", "settings");
    // Parse input string
    var curDate = $.datepicker.parseDate(format, dateText, settings);
    // If it is indeed a date
    if (typeof curDate !== "undefined") {
        // Update input field with formatted date
        $(this).datepicker("setDate", curDate);
    }
}

Additionally, if your goal is to allow multiple input date formats, see my answer here on this topic: https://stackoverflow.com/a/53499829/5426777

LePatay
  • 172
  • 1
  • 8