码迷,mamicode.com
首页 > Web开发 > 详细

js日期拓展方法

时间:2019-11-08 17:45:13      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:date   ace   offset   function   时间   ast   color   fun   获取   

最近项目中使用了大量关于日期的操作遂将其整理如下:

/**
 * 格式化日期
 * @param {String} fmt [日期类型 默认为年月日(yyyy-MM-dd)]
 */
Date.prototype.format = function (fmt = ‘yyyy-MM-dd‘) {
    var date = {
        "y+": this.getFullYear(),
        "M+": this.getMonth() + 1,
        "d+": this.getDate(), 
        "h+": this.getHours(), 
        "m+": this.getMinutes(), 
        "s+": this.getSeconds(), 
        "q+": Math.floor((this.getMonth() + 3) / 3), 
        "S": this.getMilliseconds() 
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var key in date) {
        if (new RegExp("(" + key + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (date[key]) : (("00" + date[key]).substr(("" + date[key]).length)));
        }
    }
    return fmt;
}
/**
 * 返回带有时区的时间
 * @param {String} fmt [日期类型 默认为年月日(yyyy-MM-dd hh:mm:ss)]
 */
 Date.prototype.getUtcTime = function (format = ‘yyyy-MM-dd hh:mm:ss‘) {
    return this.format(format) + ‘GMT‘ + Math.abs(new Date().getTimezoneOffset() / 60) + ‘00‘
}
/**
* 获取当前月的最后一天
* @param {String} fmt [日期类型 默认为年月日(yyyy-MM-dd)]
*/
Date.prototype.getCurrentMonthLast = function (format = ‘yyyy-MM-dd‘) {
    var currentMonth = this.getMonth();
    var nextMonth = ++currentMonth;
    var nextMonthFirstDay = new Date(this.getFullYear(), nextMonth, 1);
    var oneDay = 1000 * 60 * 60 * 24;
    return new Date(nextMonthFirstDay - oneDay).format(format);
}
/**
* 获取当前月的第一天
* @param {String} fmt [日期类型 默认为年月日(yyyy-MM-dd)]
*/
Date.prototype.getCurrentMonthFirst = function (format = ‘yyyy-MM-dd‘) {
    return new Date(this.getFullYear(), this.getMonth(), 1).format(format);
}

 

js日期拓展方法

标签:date   ace   offset   function   时间   ast   color   fun   获取   

原文地址:https://www.cnblogs.com/gionlee/p/11821793.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!