Handling Dates in VIsualforce Js Remoting

Most of the people now a days are using Javascript remoting to bring data from controller to a Visualforce page. This is one of the most fastest way using which data can be brought back to the page. Visualforce remoting makes the page light weight, more responsive and more faster.

But after all its works using js proxies, to handle dates properly dates fields are moved from back and forth the controller using doubles(not using js date objects). This makes the API clean but adds an overhead of converting them back to Date object.

If you have enough experience with Js date,  you will observe that while converting doubles into date a timezone offset is added to the actual date.some thing like  4/4/2013 at 6pm. And you can even observe a shift in date due to addition of timezone offset.

So how to handle this?
Well to fix this I wrote a simple js function which nulifies the effect by subtracting the offset back from the date.

function normalizeDate(mydate){  
   mydate = new Date(mydate );  
   mydate = new Date(mydate - mydate.getTimezoneOffset() * 60000);  
   return mydate;  

You can use the above function and try doing something like this :

//obj is record returned by js remoting   
  obj.Custom_Date__c = normalizeDate(obj.Custom_Date__c);  

You can also convert the date into readable form.using the below extended js function

function normalizeDateExtended(mydate){  
   mydate = new Date(mydate);  
   data = new Date(mydate - mydate.getTimezoneOffset() * 60000);  
   var d = mydate.getDate();  
   var m = mydate.getMonth()+1;  
   var y = mydate.getFullYear();  
   return ''+ (m<=9?'0'+m:m) +'-' + (d<=9?'0'+d:d)+'-' + y;