日期工具類

/**
 * @author: 苗士軍
 * @description 日期工具類
 */
DateUtils = {
    //模式
    patterns: {
        PATTERN_ERA: 'G', //Era 標誌符 Era strings. For example: "AD" and "BC"
        PATTERN_YEAR: 'y', //
        PATTERN_MONTH: 'M', //月份
        PATTERN_DAY_OF_MONTH: 'd', //月份的天數
        PATTERN_HOUR_OF_DAY1: 'k', //一天中的小時數(1-24)
        PATTERN_HOUR_OF_DAY0: 'H', //24小時制,一天中的小時數(0-23)
        PATTERN_MINUTE: 'm', //小時中的分鐘數
        PATTERN_SECOND: 's', //
        PATTERN_MILLISECOND: 'S', //毫秒
        PATTERN_DAY_OF_WEEK: 'E', //一週中對應的星期,如星期一,週一
        PATTERN_DAY_OF_YEAR: 'D', //一年中的第幾天
        PATTERN_DAY_OF_WEEK_IN_MONTH: 'F', //一月中的第幾個星期(會把這個月總共過的天數除以7,不夠準確,推薦用W)
        PATTERN_WEEK_OF_YEAR: 'w', //一年中的第幾個星期
        PATTERN_WEEK_OF_MONTH: 'W', //一月中的第幾星期(會根據實際狀況來算)
        PATTERN_AM_PM: 'a', //上下午標識
        PATTERN_HOUR1: 'h', //12小時制 ,am/pm 中的小時數(1-12)
        PATTERN_HOUR0: 'K', //和h類型
        PATTERN_ZONE_NAME: 'z', //時區名
        PATTERN_ZONE_VALUE: 'Z', //時區值
        PATTERN_WEEK_YEAR: 'Y', //和y類型
        PATTERN_ISO_DAY_OF_WEEK: 'u',
        PATTERN_ISO_ZONE: 'X'
    },
    week: {
        'ch': {
            "0": "日",
            "1": "一",
            "2": "二",
            "3": "三",
            "4": "四",
            "5": "五",
            "6": "六"
        },
        'en': {
            "0": "Sunday",
            "1": "Monday",
            "2": "Tuesday",
            "3": "Wednesday",
            "4": "Thursday",
            "5": "Friday",
            "6": "Saturday"
        }
    },
    /**
     * @description 獲取當前時間
     * @return {string}
     */
    getCurrentTime: function() {
        var today = new Date();
        var year = today.getFullYear();
        var month = today.getMonth() + 1;
        var day = today.getDate();
        var hours = today.getHours();
        var minutes = today.getMinutes();
        var seconds = today.getSeconds();
        var timeString = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
        return timeString;
    },
    /**
     * @description 比較時間大小
     * @param time1
     * @param time2
     * @return {number}  time1>time2 return 1 time1<time2 return -1  time1==time2 return 0
     */
    compareTime: function(time1, time2) {
        if (Date.parse(time1.replace(/-/g, "/")) > Date.parse(time2.replace(/-/g, "/"))) {
            return 1;
        } else if (Date.parse(time1.replace(/-/g, "/")) < Date.parse(time2.replace(/-/g, "/"))) {
            return -1;
        } else if (Date.parse(time1.replace(/-/g, "/")) == Date.parse(time2.replace(/-/g, "/"))) {
            return 0;
        }
    },
    /**
     * @description 是否閏年
     * @param year
     * @return {boolean}
     */
    isLeapYear: function(year) {
        return ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0);
    },
    /**
     * @description 獲取某個月的天數,從0開始
     * @param year
     * @param month
     * @return {*}
     */
    getDaysOfMonth: function(year, month) {
        return [31, (this.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
    },
    /**
     * @description 獲取某個月的天數1-12月
     * @param year
     * @param month
     * @return {*}
     */
    getDaysOfMonth2: function(year, month) {
        // 將天置爲0,會獲取其上個月的最後一天
        var date = new Date(year, month, 0);
        return date.getDate();
    },
    /**
     * @description 距離如今幾天的日期:負數表示今天以前的日期,0表示今天,整數表示將來的日期如-1表示昨天的日期,0表示今天,2表示後天
     * @param days
     * @return {string}
     */
    fromToday: function(days) {
        var today = new Date();
        today.setDate(today.getDate() + days);
        var date = today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate();
        return date;
    },
    /**
     * @description 日期時間格式化
     * @param {Object} dateTime 須要格式化的日期時間
     * @param {String} pattern  格式化的模式,如yyyy-MM-dd hh(HH):mm:ss.S a k K E D F w W z Z
     */
    formt: function(dateTime, pattern) {
        var date = new Date(dateTime);
        if (pattern == undefined || pattern =='') {
            return date.toLocaleString();
        }
        return pattern.replace(/([a-z])\1*/ig, function(matchStr, group1) {
            var replacement = "";
            switch (group1) {
                case DateUtils.patterns.PATTERN_ERA: //G
                    break;
                case DateUtils.patterns.PATTERN_WEEK_YEAR: //Y
                case DateUtils.patterns.PATTERN_YEAR: //y
                    replacement = date.getFullYear();
                    break;
                case DateUtils.patterns.PATTERN_MONTH: //M
                    var month = date.getMonth() + 1;
                    replacement = (month < 10 && matchStr.length >= 2) ? "0" + month : month;
                    break;
                case DateUtils.patterns.PATTERN_DAY_OF_MONTH: //d
                    var days = date.getDate();
                    replacement = (days < 10 && matchStr.length >= 2) ? "0" + days : days;
                    break;
                case DateUtils.patterns.PATTERN_HOUR_OF_DAY1: //k(1~24)
                    var hours24 = date.getHours();
                    replacement = hours24;
                    break;
                case DateUtils.patterns.PATTERN_HOUR_OF_DAY0: //H(0~23)
                    var hours24 = date.getHours();
                    replacement = (hours24 < 10 && matchStr.length >= 2) ? "0" + hours24 : hours24;
                    break;
                case DateUtils.patterns.PATTERN_MINUTE: //m
                    var minutes = date.getMinutes();
                    replacement = (minutes < 10 && matchStr.length >= 2) ? "0" + minutes : minutes;
                    break;
                case DateUtils.patterns.PATTERN_SECOND: //s
                    var seconds = date.getSeconds();
                    replacement = (seconds < 10 && matchStr.length >= 2) ? "0" + seconds : seconds;
                    break;
                case DateUtils.patterns.PATTERN_MILLISECOND: //S
                    var milliSeconds = date.getMilliseconds();
                    replacement = milliSeconds;
                    break;
                case DateUtils.patterns.PATTERN_DAY_OF_WEEK: //E
                    var day = date.getDay();
                    replacement = DateUtils.week['ch'][day];
                    break;
                case DateUtils.patterns.PATTERN_DAY_OF_YEAR: //D
                    replacement = DateUtils.dayOfTheYear(date);
                    break;
                case DateUtils.patterns.PATTERN_DAY_OF_WEEK_IN_MONTH: //F
                    var days = date.getDate();
                    replacement = Math.floor(days / 7);
                    break;
                case DateUtils.patterns.PATTERN_WEEK_OF_YEAR: //w
                    var days = DateUtils.dayOfTheYear(date);
                    replacement = Math.ceil(days / 7);
                    break;
                case DateUtils.patterns.PATTERN_WEEK_OF_MONTH: //W
                    var days = date.getDate();
                    replacement = Math.ceil(days / 7);
                    break;
                case DateUtils.patterns.PATTERN_AM_PM: //a
                    var hours24 = date.getHours();
                    replacement = hours24 < 12 ? "上午" : "下午";
                    break;
                case DateUtils.patterns.PATTERN_HOUR1: //h(1~12)
                    var hours12 = date.getHours() % 12 || 12; //0轉爲12
                    replacement = (hours12 < 10 && matchStr.length >= 2) ? "0" + hours12 : hours12;
                    break;
                case DateUtils.patterns.PATTERN_HOUR0: //K(0~11)
                    var hours12 = date.getHours() % 12;
                    replacement = hours12;
                    break;
                case DateUtils.patterns.PATTERN_ZONE_NAME: //z
                    replacement = DateUtils.getZoneNameValue(date)['name'];
                    break;
                case DateUtils.patterns.PATTERN_ZONE_VALUE: //Z
                    replacement = DateUtils.getZoneNameValue(date)['value'];
                    break;
                case DateUtils.patterns.PATTERN_ISO_DAY_OF_WEEK: //u
                    break;
                case DateUtils.patterns.PATTERN_ISO_ZONE: //X
                    break;
                default:
                    break;
            }
            return replacement;
        });
    },
    /**
     * @description 計算一個日期是當年的第幾天
     * @param {Object} date
     */
    dayOfTheYear: function(date) {
        var obj = new Date(date);
        var year = obj.getFullYear();
        var month = obj.getMonth(); //從0開始
        var days = obj.getDate();
        var daysArr = [31, (this.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        for (var i = 0; i < month; i++) {
            days += daysArr[i];
        }
        return days;
    },
    /**
     * @description 得到時區名和值
     * @param dateObj
     * @return {{name: *, value: *}}
     */
    getZoneNameValue: function(dateObj) {
        var date = new Date(dateObj);
        date = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
        var arr = date.toString().match(/([A-Z]+)([-+]\d+:?\d+)/);
        var obj = {
            'name': arr[1],
            'value': arr[2]
        };
        return obj;
    }
};
相關文章
相關標籤/搜索