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?
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:
UserInfo.getTimezone()
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;
};
DateUtil
can be found by viewing sources in Chrome jslibrary/.../sfdc/main.js
which says "This code is for Internal Salesforce use only, and subject to change without notice. Customers shouldn't reference this file in any web pages.". So there is a risk of Salesforce changing or removing that DateUtil
in future releases.
Commented
Jul 27, 2016 at 18:35
UserInfo.getTimezone()
instead
Commented
Jul 27, 2016 at 18:38
It's actually a Date value, so you can call normal Date methods on it. Use a locale-safe option that respects month/day and day/month output by having the browser figure it out for you:
var dateString = result.dateValue.toLocaleDateString();