[SalesForce] VisualForce – JavaScript formatting of date returned using Remote Object retrieve

So using a remote object retrieve I am receiving a date in the following format:

Wed May 06 2015 00:00:00 GMT-0700 (PDT)

What's the best way to format this as MM/DD/YYYY using JavaScript?

Best Answer

Do not rely on the browser here. Using the browser assumes that your user is working on a computer set to the same timezone as the UserInfo data. This is generally not true when you have someone working from a hotel business center a timezone away.

You can do one of two things here:

  1. Create your own JavaScript method taking into account UserInfo.getTimezone()
  2. Use these undocumented methods that are exposed in Salesforce but subject to change and not officially part of the API:

    • DateUtil.getDateTimeStringFromUserLocale(result) returns a string representation.

    • DateUtil.getDateTimeFromUserLocale(value) will read that string and turn it back into a JavaScript Date object, but make sure that you set the seconds and milliseconds to 0 because this method's Date result will default to whatever value new Date() says for those fields.

Note also, either way, before you write a date that there is a bug in VF Remoting:

VFRemoting demands datetimes to be in UTC. You cannot include an offset.

Erroneous details are in VFRemote.js: VFExt3.util.JSON.encodeDate which neglects to append the timezone offset of a javascript Date.

So to write a date using VF Remoting, please make sure to do the following before you write to the database:

  var adjustTime = function (time) {
    if (time) {
      var newTime = new Date(time);
      newTime.setMinutes(time.getMinutes()+time.getTimezoneOffset());
      return newTime;
    }
    return time;
  };
Related Topic