Javascript remoting and apex date design pattern

I’d like a clever way to handle this in all my code from now on.

I have some existing methods that do date calculations in apex…some use the businessHours object and some don’t. Many surface results to visualforce pages and work nicely.

When I retrieve them by jsRemoting, I get back javascript date, which is really date time. So if my apex date is 4/5/2013, I’m getting back 4/4/2013 at 6pm…it like it took the apex date at midnight (start of the day) and timeline shifted it for US central time (my locale).

It gets even uglier when I have to validate do jquery mobile html form stuff…so I’m converting that date time in JS to a string to prepopulate a form field. Then depending on what the user enters, I have to validate it against a min/man date from apex…and I’m dealing with the date being ok, but depending on what times are entered, the hours being not ok.

Is there a way to “fix” what comes back from apex? Or am I better off doing all this on the client side? JS date manipulation is not as elegant as apex.

Answer

Well I came across this problem and this gets uglier when you are converting the double value returned from apex into date, the timezone offset gets added into the time and can even change the date!!!.

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 even extend the above js function to print a date string

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;
}

Attribution
Source : Link , Question Author : Shane McLaughlin , Answer Author : Avidev9

Leave a Comment