I have a Date
object. How do I render the title
portion of the following snippet?
I typically don't want to display a UTC date since customers don't like doing the conversion in their head. To display a local ISO date, I use the function:
function toLocalIsoString(date, includeSeconds) {
function pad(n) { return n < 10 ? '0' + n : n }
var localIsoString = date.getFullYear() + '-'
+ pad(date.getMonth() + 1) + '-'
+ pad(date.getDate()) + 'T'
+ pad(date.getHours()) + ':'
+ pad(date.getMinutes()) + ':'
+ pad(date.getSeconds());
if(date.getTimezoneOffset() == 0) localIsoString += 'Z';
return localIsoString;
};
The function above omits time zone offset information (except if local time happens to be UTC), so I use the function below to show the local offset in a single location. You can also append its output to results from the above function if you wish to show the offset in each and every time:
function getOffsetFromUTC() {
var offset = new Date().getTimezoneOffset();
return ((offset < 0 ? '+' : '-')
+ pad(Math.abs(offset / 60), 2)
+ ':'
+ pad(Math.abs(offset % 60), 2))
};
toLocalIsoString
uses pad
. If needed, it works like nearly any pad function, but for the sake of completeness this is what I use:
// Pad a number to length using padChar
function pad(number, length, padChar) {
if (typeof length === 'undefined') length = 2;
if (typeof padChar === 'undefined') padChar = '0';
var str = "" + number;
while (str.length < length) {
str = padChar + str;
}
return str;
}