It's necessary to consider the timezone when determining which date it is. I assume that the first part of the date is the output from Date.getTime()
of Java or JavaScript (i.e. the number of milliseconds since January 1, 1970, 00:00:00 UTC).
For the correct output for all times on a date, it is necessary to apply the timezone offset (e.g. -0500
for Eastern Standard Time) before creating the Date object and then use the UTC methods to get parts of the date. The reason is that JavaScript does not provide a Date.setTimezoneOffset()
method to set the timezone to the correct one (it's not possible to change it from the visitor's system timezone).
Code example
Here's the code I came up with. It uses a regex to extract the parts of the encoded date, applies the specified timezone offset, creates a Date object, and then builds a date from the parts (demo: http://jsfiddle.net/Wa8LY/1/).
var dateParts = data[0].StartDate.match(/\((.*)([+-])(..)(..)\)/);
var dateObj = new Date(
/* timestamp in milliseconds */ Number(dateParts[1]) +
/* sign of timezone offset */ Number(dateParts[2] + '1') *
/* hours and minutes offset */ (36e5 * dateParts[3] + 6e4 * dateParts[4])
);
var dateMMDDYYYY = [dateObj.getUTCMonth() + 1,
dateObj.getUTCDate(),
dateObj.getUTCFullYear()].join('/');
Left padding the components
If you need to left pad the components of the date (e.g. 01/01/0001
), you could use this function to help do so:
function leftPadWithZeroes(str, len) {
return (new Array(len + 1).join('0') + str).slice(-len);
}
And change the last lines to (demo: http://jsfiddle.net/5tkpV/1/):
var dateMMDDYYYY = [leftPadWithZeroes(dateObj.getUTCMonth() + 1, 2),
leftPadWithZeroes(dateObj.getUTCDate(), 2),
leftPadWithZeroes(dateObj.getUTCFullYear(), 4)].join('/');