date

88 阅读1分钟

时间函数

parse2Date()

// 时间字符转成 "2018-12-12"的形式 显示
function parse2Date(cellValue) {
    if (cellValue === undefined || cellValue === "") {
        return "";
    }
    let date = new Date(Date.parse(cellValue.replace(/-/g, "/")));
    return (
        date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate()
    );
}

date2Str()

// Date 对象 转成 "2018-12-12"的形式 显示
function date2Str(date) {
    if (date === undefined || !(date instanceof Date)) {
        return "";
    }  
    return (
        date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate()
    );
} 

date2TimeStrZero()

// Date 对象 转成 '2018-12-12 10:00:00'的形式 显示 补0的  带时分秒
function date2TimeStrZero(dateObj) {
    if (dateObj === undefined || !(dateObj instanceof Date)) {
        return "";
    }
    return (
        dateObj.getFullYear() +
        "-" +
        String(dateObj.getMonth() + 1).padStart(2, "0") +
        "-" +
        String(dateObj.getDate()).padStart(2, "0") +
        " " +
        String(dateObj.getHours()).padStart(2, "0") +
        ":" +
        String(dateObj.getMinutes()).padStart(2, "0") +
        ":" +
        String(dateObj.getSeconds()).padStart(2, "0")
    );
}

date2Time()

// Date 对象 转成 '10:00:00'的形式 显示     补0的
function date2Time(dateObj) {
    if (dateObj === undefined || !(dateObj instanceof Date)) {
        return "";
    }
    return (
        String(dateObj.getHours()).padStart(2, "0") +
        ":" +
        String(dateObj.getMinutes()).padStart(2, "0") +
        ":" +
        String(dateObj.getSeconds()).padStart(2, "0")
    );
}

formatDate()

// 时间格式化为yyyy-MM-dd
function formatDate(value) {
    let arr = [];
    arr.push(value.getFullYear());
    arr.push(
        value.getMonth() + 1 < 10
            ? "0" + (value.getMonth() + 1)
            : value.getMonth() + 1
    );
    arr.push(value.getDate() < 10 ? "0" + value.getDate() : value.getDate());
    return arr.join("-");
}

date2Str()

// Date 对象 转成 "2018-12-12"的形式 显示
function date2Str(dateObj) {
    if (dateObj === undefined || !(dateObj instanceof Date)) {
        return "";
    } 
    let str =`${dateObj.getFullYear()}-${dateObj.getMonth()+1}-${dateObj.getDate()}` ; 
    return str;
}