JavaScript 时间帮助封装

前端JS 时间帮助类封装
/*
 * @Description: 日期时间帮助工具
 * @Author: SkyPillar
 * @Date: 2020-05-22 11:09:32
 * @LastEditTime: 2020-05-22 14:43:17
 * @LastEditors: SkyPillar
 */
var DateHelper;
(function (DateHelper) {
    /**
     * 混淆
     */
    var Confuse = /** @class */ (function () {
        function Confuse() {
        }
        /**
         * 加密字符串
         * @param code 字符串
         */
        Confuse.prototype.compileStr = function (code) {
            if (code)
                return '';
            var o = String.fromCharCode(code.charCodeAt(0) + code.length);
            for (var i = 1; i < code.length; i++)
                o += String.fromCharCode(code.charCodeAt(i) + code.charCodeAt(i - 1));
            return escape(o);
        };
        /**
         * 解密字符串
         * @param code 字符串
         */
        Confuse.prototype.uncompileStr = function (code) {
            code = unescape(code);
            var o = String.fromCharCode(code.charCodeAt(0) - code.length);
            for (var i = 1; i < code.length; i++)
                o += String.fromCharCode(code.charCodeAt(i) - o.charCodeAt(i - 1));
            return o;
        };
        return Confuse;
    }());
    /**
     * 本地缓存
     */
    var Storage = /** @class */ (function () {
        function Storage() {
            this.confuse = new Confuse();
            this.storage = window.localStorage;
        }
        /**
         * 设置内存对象
         * @param key 字符串
         * @param value 字符串
         */
        Storage.prototype.setStorage = function (key, value) {
            if (key === null)
                return console.error('must be a string or integer parameter');
            if (!value) {
                var val = value.trim();
                if (val === '')
                    this.storage.setItem(key, val);
                else
                    this.storage.setItem(key, this.confuse.compileStr(val));
            }
            else
                this.storage.removeItem(key);
        };
        /**
         * 根据key获取对应内容
         * @param key 字符串
         */
        Storage.prototype.getStorage = function (key) {
            if (key === '')
                return null;
            var o = this.storage.getItem(key);
            if (o === null)
                return '';
            else
                return this.confuse.uncompileStr(o);
        };
        /**
         * 根据key 删除对应的内容
         * @param key 字符串
         */
        Storage.prototype.removeStorage = function (key) {
            if (key !== '')
                this.storage.removeItem(key);
        };
        return Storage;
    }());
    /**
     * 计算帮助类
     */
    var Computer = /** @class */ (function () {
        function Computer() {
        }
        /**
         * 计算十位补零
         * @param o 整型
         */
        Computer.prototype.constituted = function (o) {
            return o < 10 ? '0' + o : o;
        };
        return Computer;
    }());
    /**
     * 私有帮助类
     */
    var Assisted = /** @class */ (function () {
        function Assisted() {
            /**
             * 临时变量
             */
            this.arr = new Array();
            /**
             * 星期
             */
            this.week = '星期';
            /**
             * 日
             */
            this.day = '';
            /**
             * 本地缓存
             */
            this.storage = new Storage();
            /**
             * 计算函数
             */
            this.computer = new Computer();
        }
        /**
         * 年月日时分秒汉字
         */
        Assisted.prototype.getSpecificDate = function () {
            this.arr = new Array();
            this.arr.push('', '', this.day, '', '', '');
            return this.arr;
        };
        /**
         * 农历十位汉字
         */
        Assisted.prototype.getCapitalizedTen = function () {
            this.arr = new Array();
            this.arr.push('', '', '廿', '');
            return this.arr;
        };
        /**
         * 大写阿拉伯数字
         */
        Assisted.prototype.getCapitalizedNumber = function () {
            this.arr = new Array();
            this.arr.push('', '', '', '', '', '', '', '', '', '', '');
            return this.arr;
        };
        /**
         * 十二生肖
         */
        Assisted.prototype.getChineseZodiac = function () {
            this.arr = new Array();
            this.arr.push('', '', '', '', '', '', '', '', '', '', '', '');
            return this.arr;
        };
        /**
         * 十二地支
         */
        Assisted.prototype.getTwelveEarthlyBranch = function () {
            this.arr = new Array();
            this.arr.push('', '', '', '', '', '', '', '', '', '', '', '');
            return this.arr;
        };
        /**
         * 十干支
         */
        Assisted.prototype.getTenBranches = function () {
            this.arr = new Array();
            this.arr.push('', '', '', '', '', '', '', '', '', '');
            return this.arr;
        };
        /**
         * 获取日期时间数组
         * @param paramDate 日期时间参数
         * @param isHms 是否显示时分秒
         */
        Assisted.prototype.getDateArray = function (dateStr, isHms) {
            if (dateStr === void 0) { dateStr = null; }
            if (isHms === void 0) { isHms = true; }
            this.arr = new Array();
            dateStr = (!dateStr) ? new Date() : dateStr;
            this.arr.push(dateStr.getFullYear(), this.computer.constituted(dateStr.getMonth() + 1), this.computer.constituted(dateStr.getDate()));
            if (!isHms)
                this.arr.push(this.computer.constituted(dateStr.getHours()), this.computer.constituted(dateStr.getMinutes()), this.computer.constituted(dateStr.getSeconds()));
            return this.arr;
        };
        /**
         * 根据指定的时间获取天
         * @param dataStr 日期时间
         */
        Assisted.prototype.getDateDay = function (dataStr) {
            if (dataStr === void 0) { dataStr = null; }
            var res = (!dataStr) ? new Date() : dataStr;
            return res.getDay();
        };
        /**
         * 十二生肖与地支
         */
        Assisted.prototype.getBranchesAndZodiacArrays = function () {
            var zodiacArr = this.getChineseZodiac();
            var branchArr = this.getTwelveEarthlyBranch();
            if (zodiacArr.length !== branchArr.length)
                throw 'wrong length of chinese zodiac and branches';
            this.arr = new Array();
            for (var i = 0; i < branchArr.length; i++)
                this.arr.push(branchArr[i] + zodiacArr[i]);
            return this.arr;
        };
        /**
         * 十二生肖和地支
         * @param symbol 分割符
         */
        Assisted.prototype.getTwelveZodiacSignsAndBranches = function (symbol) {
            if (symbol === void 0) { symbol = null; }
            this.arr = this.getBranchesAndZodiacArrays();
            return (!symbol) ? this.arr : this.arr.join(symbol);
        };
        /**
         * 获取星期
         */
        Assisted.prototype.getWeeks = function () {
            var numArr = this.getCapitalizedNumber();
            this.arr = new Array();
            this.arr.push(this.week + this.day);
            for (var i = 1; i < 7; i++)
                this.arr.push(this.week + numArr[i]);
            return this.arr;
        };
        /**
         * 获取六十甲子
         * @param symbol 分割符号
         * @param isArr 是否返回数组(默认数组)
         */
        Assisted.prototype.getSixties = function (symbol, isArr) {
            if (symbol === void 0) { symbol = null; }
            if (isArr === void 0) { isArr = true; }
            var ramus = this.getTenBranches();
            var earthlyBranch = this.getTwelveEarthlyBranch();
            var ramusLen = ramus.length, earthlyBranchLen = earthlyBranch.length, i = 0, j = 0;
            this.arr = new Array();
            while (1) {
                var x = i % ramusLen, y = j % earthlyBranchLen;
                if (x == 0 && y == 0 && i)
                    break;
                this.arr.push(ramus[x] + earthlyBranch[y]);
                i++;
                j++;
            }
            return isArr ? this.arr : this.arr.join(symbol);
        };
        /**
         * 切换大小写数字
         * @param param 大小写数字
         */
        Assisted.prototype.getNumberToggleCase = function (param) {
            if (!param && param != '0')
                return console.error('wrong number parameter to convert');
            var numArr = this.getCapitalizedNumber();
            var result = numArr[param];
            return typeof result === 'undefined' ? numArr.indexOf(param) : result;
        };
        /**
         * 获取年月日-(yyyy年MM月dd日)
         * @param isHms 是否显示时分秒
         */
        Assisted.prototype.getChineseDateString = function (isHms) {
            if (isHms === void 0) { isHms = true; }
            var dateArr = this.getDateArray(null, isHms);
            var yMds = this.getSpecificDate();
            var result = String();
            for (var i = 0; i < dateArr.length; i++) {
                if (!isHms && i === 2)
                    result += dateArr[i] + yMds[i] + ' ';
                else
                    result += dateArr[i] + yMds[i];
            }
            return result;
        };
        /**
         * 获取工作日(星期)
         * @param day 天
         */
        Assisted.prototype.getWorkDay = function (day) {
            return this.getWeeks()[day];
        };
        /**
         * 获取工作日期(yyyy年MM月dd日)
         */
        Assisted.prototype.getWorkingDateStr = function () {
            var dateArr = this.getDateArray(null, true);
            var yMds = this.getSpecificDate();
            var dayNum = this.getDateDay();
            var result = String();
            for (var i = 0; i < dateArr.length; i++)
                result += dateArr[i] + yMds[i];
            return result + ' ' + this.getWorkDay(dayNum);
        };
        /**
         * 获取时分秒
         */
        Assisted.prototype.getChineseHourMinuteSecond = function () {
            var dateArr = this.getDateArray(null, false);
            var yMds = this.getSpecificDate();
            var result = String();
            for (var i = 3; i < dateArr.length; i++)
                result += dateArr[i] + yMds[i];
            return result;
        };
        /**
         * 获取时分秒
         */
        Assisted.prototype.getHourMinuteSecond = function () {
            var dateArr = this.getDateArray(null, false);
            this.arr = new Array();
            var result = String();
            for (var i = 3; i < dateArr.length; i++)
                this.arr.push(dateArr[i]);
            return this.arr.join(':');
        };
        /**
         * 封装时间格式化
         * @param paramDate 时间日期对象
         * @param isHms 默认为年月日
         */
        Assisted.prototype.getDateTime = function (paramDate, mow, isHms) {
            if (mow === void 0) { mow = null; }
            if (isHms === void 0) { isHms = true; }
            var dateArr = this.getDateArray(paramDate, isHms);
            var result = String();
            if (!mow) {
                for (var i = 0; i < dateArr.length; i++)
                    result += dateArr[i];
            }
            else {
                if (isHms) {
                    for (var i = 0; i < dateArr.length; i++)
                        result += dateArr[i] + mow;
                    result = result.substring(result.lastIndexOf(mow), 0);
                }
                else {
                    for (var i = 0; i < dateArr.length; i++) {
                        if (i === 3) {
                            result = result.substring(result.lastIndexOf(mow), 0) + ' ';
                            mow = ':';
                        }
                        result += dateArr[i] + mow;
                    }
                    result = result.substring(result.lastIndexOf(mow), 0);
                }
            }
            return result;
        };
        /**
         * 验证字符串内容是否为空
         * @param str
         */
        Assisted.prototype.isNullOrEmpty = function (str) {
            if (str !== null && str !== '') {
                str = str.trim();
                if (str === '')
                    return false;
                return true;
            }
            else
                return false;
        };
        return Assisted;
    }());
    /**
     * 时间帮助类
     */
    var DateUtils = /** @class */ (function () {
        function DateUtils() {
            /**
             * 私有帮助变量
             */
            this.asted = new Assisted();
        }
        /**
         * 获取当前时间戳
         */
        DateUtils.prototype.getTimeStamp = function () {
            return new Date().getTime();
        };
        /**
         * 获取当前时间
         * @param mow 日期分割符号允许空字符串(空字符串返回日期时间戳)
         * @param isHms 默认为年月日
         */
        DateUtils.prototype.getCurrentTime = function (mow, isHms) {
            if (mow === void 0) { mow = null; }
            if (isHms === void 0) { isHms = true; }
            return this.asted.getDateTime(null, mow, isHms);
        };
        /**
         * 获取指定的当前时间
         * @param sort 时间格式年月日时分秒(yyyy=年,MM=月,dd=日,HH=时,mm=分,ss=秒)
         * @param symbol 计算符号
         * @param num 指定时间
         * @param mow 日期分隔符
         * @param isHms 默认为年月日
         */
        DateUtils.prototype.getSpecifiedTime = function (sort, symbol, num, mow, isHms) {
            if (mow === void 0) { mow = null; }
            if (isHms === void 0) { isHms = true; }
            var myDate = new Date();
            var sortErr = 'abnormal time format';
            switch (symbol) {
                case '':
                case '+':
                    switch (sort) {
                        case '':
                        case 'yyyy':
                            myDate.setFullYear(new Date().getFullYear() + num);
                            break;
                        case '':
                        case 'MM':
                            myDate.setMonth(new Date().getMonth() + num);
                            break;
                        case '':
                        case 'dd':
                            myDate.setDate(new Date().getDate() + num);
                            break;
                        case '':
                        case 'HH':
                            myDate.setHours(new Date().getHours() + num);
                            break;
                        case '':
                        case 'mm':
                            myDate.setMinutes(new Date().getMinutes() + num);
                            break;
                        case '':
                        case 'ss':
                            myDate.setSeconds(new Date().getSeconds() + num);
                            break;
                        default:
                            return console.error(sortErr);
                    }
                    break;
                case '':
                case '-':
                    switch (sort) {
                        case '':
                        case 'yyyy':
                            myDate.setFullYear(new Date().getFullYear() - num);
                            break;
                        case '':
                        case 'MM':
                            myDate.setMonth(new Date().getMonth() - num);
                            break;
                        case '':
                        case 'dd':
                            myDate.setDate(new Date().getDate() - num);
                            break;
                        case '':
                        case 'HH':
                            myDate.setHours(new Date().getHours() - num);
                            break;
                        case '':
                        case 'mm':
                            myDate.setMinutes(new Date().getMinutes() - num);
                            break;
                        case '':
                        case 'ss':
                            myDate.setSeconds(new Date().getSeconds() - num);
                            break;
                        default:
                            return console.error(sortErr);
                    }
                    break;
                default:
                    return console.error('incorrect calculation symbol entered');
            }
            return this.asted.getDateTime(myDate, mow, isHms);
        };
        /**
         * 获取时间(yyyy年MM月dd日)
         * @param isHms 默认为年月日
         */
        DateUtils.prototype.getChineseDate = function (isHms) {
            if (isHms === void 0) { isHms = true; }
            return this.asted.getChineseDateString(isHms);
        };
        /**
         * 获取时分秒(HH时mm分ss秒)
         */
        DateUtils.prototype.getChineseHMS = function () {
            return this.asted.getChineseHourMinuteSecond();
        };
        /**
         * 获取时分秒(HH:mm:ss)
         */
        DateUtils.prototype.getHMS = function () {
            return this.asted.getHourMinuteSecond();
        };
        /**
         * 根据指定的时间获取星期(默认今天)
         * @param timestamp 日期时间戳
         */
        DateUtils.prototype.getWorkDate = function (timestamp) {
            if (timestamp === void 0) { timestamp = null; }
            var myDate = new Date();
            if (this.asted.isNullOrEmpty(timestamp))
                try {
                    if (this.asted.isNullOrEmpty(timestamp) && !isNaN(Date.parse(timestamp)))
                        myDate = new Date(timestamp);
                    else
                        throw 'not a time date format';
                }
                catch (error) {
                    return console.error(error);
                }
            return this.asted.getWeeks()[myDate.getDay()];
        };
        /**
         * 获取工作时间(yyyy年MM月dd日 星期)
         */
        DateUtils.prototype.getWorkingDate = function () {
            return this.asted.getWorkingDateStr();
        };
        /**
         * 获取生肖
         * @param symbol 分隔符号(默认数组)
         */
        DateUtils.prototype.getBranchesZodiac = function (symbol) {
            if (symbol === void 0) { symbol = null; }
            return this.asted.getTwelveZodiacSignsAndBranches(symbol);
        };
        /**
         * 格式化时间戳
         * @param timestamp 时间戳
         * @param mow 指定格式
         * @param isHms 默认为年月日
         */
        DateUtils.prototype.formatTimestamp = function (timestamp, mow, isHms) {
            if (mow === void 0) { mow = null; }
            if (isHms === void 0) { isHms = true; }
            var timeLen = timestamp.toString().length;
            timestamp = timeLen > 10 ? timestamp : timestamp * 1000;
            var myDate = new Date(timestamp);
            return this.asted.getDateTime(myDate, mow, isHms);
        };
        return DateUtils;
    }());
    DateHelper.DateUtils = DateUtils;
})(DateHelper || (DateHelper = {}));
var myDate = new DateHelper.DateUtils();
原文地址:https://www.cnblogs.com/FGang/p/12954905.html