[SalesForce] Why is Task ActivityDate (Due Date) different when queried using SOQL

When I query a Task's ActivityDate in Apex accessed using JavaScript Remoting, I receive a date that is different from the date displayed in the Salesforce interface.

The query below (with a generic Account Id) results in 2012-09-11 for a specific Task, but the date is displayed as 9/12/2012 when viewing the Task in the Salesforce interface. It seems all ActivityDate fields for all Tasks are different by a day.

SELECT Id, AccountId, Account.Name, Priority, Status, Subject, ActivityDate, Type, 
Owner.Name, Owner.Id, What.Name, WhatId, WhoId, Who.Name, LastModifiedDate FROM Task 
WHERE AccountId IN ('001000000000000')

The time-zone of the User accessing Salesforce through the interface and through SOQL is the same – (GMT-05:00) Central Daylight Time (America/Chicago).

Does anyone have advice on how I can account for this in Apex or JavaScript (without Visualforce; I'm using Remote Actions)?

Best Answer

Javascript remoting returns dates in milliseconds since epoch. The javascript date constructor interprets the milliseconds since epoch as a date time in your local time zone, thus the discrepancy. Use the following function to correct the date:

var ONE_MINUTE = 60000;
...
function epochToDate(jsRemotingResult) {
  var epochDate = new Date(jsRemotingResult);
  return new Date(epochDate.getTime() + epochDate.getTimezoneOffset() * ONE_MINUTE);
}
Related Topic