LOADING

【笔记】JavaScript 之日期对象的使用—如何封装一个本地化时间函数

Date() 构造函数

Date 对象由新的 Date() 构造函数创建。

有 4 种方法创建新的日期对象:

new Date()
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(milliseconds)
new Date(date string)

日期格式化方法

方法名说明
getFullYear()获取当年
getMonth()获取当月(0-11)
getDate()获取当天日期
getDay()获取星期(周日 0 - 周六 6)
getHours()获取当前小时
getMinutes()获取当前分钟
getSeconds()获取当前秒钟

P.S: getMonth()方法是从0开始的 0表示1月,getDay()也是从0开始的,0表示周日

封装一个返回本地化时间的函数

原生Date()方法输出结果:

console.log(Date());
Tue Dec 14 2021 16:48:57 GMT+0800 (中国标准时间)

完全不Chinese呀 :鹿乃_???:

进行本地格式化封装

function KanoDate() {
    this.getFullYear = function() {
        var date = new Date();
        return date.getFullYear();
    }
    this.getMonth = function() {
        var date = new Date();
        var month = date.getMonth();
        month = month < 10 ? '0' + month : month;
        return month;
    }
    this.getDate = function() {
        var date = new Date();
        var dt = date.getDate();
        dt = dt < 10 ? '0' + dt : dt;
        return dt;
    }
    this.getDay = function() {
        var date = new Date();
        var day = date.getDay();
        var daylist = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        return daylist[day];
    }
    this.getHours = function() {
        var date = new Date();
        var hours = date.getHours();
        hours = hours < 10 ? '0' + hours : hours;
        return hours;
    }
    this.getMinutes = function() {
        var date = new Date();
        var minutes = date.getMinutes();
        minutes = minutes < 10 ? '0' + minutes : minutes;
        return minutes;
    }
    this.getSeconds = function() {
        var date = new Date();
        var seconds = date.getSeconds();
        seconds = seconds < 10 ? '0' + seconds : seconds;
        return seconds;
    }
    return this.getFullYear() + '-' + this.getMonth() + '-' + this.getDate() + ' ' + this.getDay() + ' ' + this.getHours() + ':' + this.getMinutes() + ':' + this.getSeconds();
}

效果:

KanoDate();
输出:'2021-11-14 星期二 17:41:08'
var day = new KanoDate();
day.getDay()
输出:'星期二'

    发表回复

    电子邮件地址不会被公开。必填项已用 * 标注