function getLocalTimeComponents(date) {
    date = date instanceof Date ? date : new Date(date);

    if (Number.isNaN(date.getTime()))
        return {};

    let components = {};

    components.date = [ date.getFullYear(), date.getMonth() + 1, date.getDate() ]
        .map(value => (value < 10 ? '0' : '') + value)
        .join('-');

    components.time = [ date.getHours(), date.getMinutes(), date.getSeconds() ]
        .map(value => (value < 10 ? '0' : '') + value)
        .join(':');

    let tz = { offset: date.getTimezoneOffset() };
    tz.sign = tz.offset > 0 ? '-' : '+';
    tz.absOffset = Math.abs(tz.offset);
    tz.hours = Math.floor(tz.absOffset/60);
    tz.minutes = tz.absOffset - 60*tz.hours;

    components.timezone = tz.sign + [ tz.hours, tz.minutes ]
        .map(value => (value < 10 ? '0' : '') + value)
        .join(':');

    return components;
}

function render(element) {
    if (!element || !element.dataset.date)
        return;

    let dateComponents = getLocalTimeComponents(element.dataset.date);

    element.innerHTML = [ 'date', 'time', 'timezone' ]
        .map(type => `<span class="${type}">${dateComponents[type]}</span>`)
        .join(' ');
}

function renderAll() {
    Array.from(document.querySelectorAll('[data-date]')).forEach(render);
}

renderAll();

export default { render };