Tuesday, 25 September 2012

Populating date obtained from server on a web page depending on capability of browser

 With the increasing use of JavaScript client libraries and advanced capabilities of browsers, a lot of logic is put on the client side. Dates are always there to bug the developers. Most of the times, we struggle with displaying a date value on the screen or getting the value from the page and sending it back to server.

I recently struggled with displaying a date value on browser. The issue was because of the following reasons:

  • Format of the date
  • Support of HTML5 datetime field

The datetime field is currently supported only by the Opera browser. On other browsers, I wanted to use jQuery UI’s datetime picker widget.
I have the following input element on my form:

<input type="datetime" id="currentDate" />

On unsupported browsers, this field appears as a textbox. Using the JavaScript library Modernizr, we can find if a feature is supported on a browser. The following script checks if datetime field is supported. If it is not supported, it adds the datetime picker widget to the field:
if(!Modernizr.inputtypes.datetime){
     currentDate.datepicker();
}

 The default format of date in .NET is MM-dd-yyyy hh:mm:ss (e.g. 07-25-2012 00:00:00). Format of the date used by Opera’s datetime field is: yyyy-dd-MMThh:mm:ssZ. This conversion is not very easy if we use JavaScript’s Date data type. DateJS library makes this conversion very easy.
var parsedDate=Date.parse("07-25-2012 00:00:00");
var currentDate = $("#currentDate");
currentDate.val(parsedDate.toJSONString());

The function toJSONString() used in the above snippet returns date in yyyy-dd-MMThh:mm:ssZ format.

Default date format used by the datepicker widget is MM/dd/yyyy. Following script sets the value of date in this format to the datepicker.
currentDate.datepicker();
currentDate.val((parsedDate.getMonth()+1)+"/"+parsedDate.getDate()+"/"+parsedDate.getFullYear());
Following is the consolidated script:
$(function(){
    var parsedDate=Date.parse("07-25-2012 00:00:00");
    var currentDate = $("#currentDate");
    currentDate.val(parsedDate.toJSONString());
		
    if(!Modernizr.inputtypes.datetime){
        currentDate.datepicker();
        currentDate.val((parsedDate.getMonth()+1)+"/"+parsedDate.getDate()+"/"+parsedDate.getFullYear());			
    }
});


Happy coding!

No comments:

Post a Comment