formatTime.js 1.08 KB
function getDateList(date) {
    if (!date) {
        return [];
    }

    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();

    return [year, month, day];
}

function formatN(format, num) {
    let n = num + '';
    let nList = n.split('');
    let l = nList.length;
    let fl = format.length;

    if (format.length < nList.length) {
        return nList;
    }

    let el = fl - l;

    for (let i = 0; i < el; i++) {
        nList.splice(0, 0, '0');
    }

    return nList.join('');
}

function formatTime(start, end) {
    let startTime = new Date(start * 1000);
    let endTime = new Date(end * 1000);

    let startDate = getDateList(startTime);
    let endDate = getDateList(endTime);

    let startDateFormat = startDate[0] + '.' + formatN('00', startDate[1]) + '.' + formatN('00', startDate[2]);
    let endDateFormat = '-' + formatN('00', endDate[1]) + '.' + formatN('00', endDate[2]);

    if (!end) {
        return '即将上线:' + startDateFormat;
    }

    return startDateFormat + endDateFormat;
}

module.exports = formatTime;