JavaScript 自定义获取当前日期和时间的函数

JavaScript 自定义获取当前日期和时间的函数

 

/**
     * 获取当前的日期和时间
     * 格式为 yyyy-MM-dd HH:mm:ss.SSS
     */
    function getNowDateTime() {
        var now = new Date
        , year = now.getFullYear()
        , month = now.getMonth() + 1
        , day = now.getDate()
        , hours = now.getHours()
        , minutes = now.getMinutes()
        , seconds = now.getSeconds()
        , milliseconds = now.getMilliseconds();

        month >= 1 && month <= 9 && (month = "0" + month),
        day > 0 && day <= 9 && (day = "0" + day),
        hours >= 0 && hours <= 9 && (hours = "0" + hours),
        minutes >= 0 && minutes <= 9 && (minutes = "0" + minutes),
        seconds >= 0 && seconds <= 9 && (seconds = "0" + seconds);

        return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds + "." + milliseconds
    }

 

console.log('当前日期和时间 = ', getNowDateTime())
posted @ 2025-01-22 14:17  hapday  阅读(27)  评论(0)    收藏  举报