Date formatting when using JavaScript Remoting in visualforce

Visualforce remoting is a method to invoke apex code through the javascript of the visualforce page.

One scenario where time is returned in the micro seconds format & needs to be converted in to the proper datetime. To do this I have just framed javascript method which will convert this number in to salesforce datetime format "MM/DD/YYYY HH:MM AM/PM"

ex. CreatedDate : 1482238284000

O/p : 12/20/2016 6:21 PM

function formatDate(dateInMicroSeconds) {
var vDate = (new Date(dateInMicroSeconds)).toLocaleString().replace(', ', ' ');
vDate = vDate.slice(0, vDate.indexOf(':') + 3) + vDate.slice(vDate.indexOf(':') + 6);
alert('vDate ' + vDate);
return vDate;
}
/*****
Above method will support only latest browsers, You can check more details in the following link:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
stable javascript formating can be done using following method:
******/
function formatDate(dateInMicroSeconds){
var vDate = new Date(dateInMicroSeconds);
var format = 'AM';
var hour = vDate.getHours();
var min = vDate.getMinutes();
if (hour > 11) format = 'PM';
if (hour > 12) hour = hour - 12;
if (hour == 0) hour = 12;
if (min < 10) min = '0' + min;
var finalDateTime = (vDate.getMonth() + 1) + '/' + vDate.getDate() + '/' + vDate.getFullYear() + ' ' + hour + ':' + min + ' ' + format;
return finalDateTime;
}
view raw formatDate.js hosted with ❤ by GitHub

Comments