JS常用时间处理 -获取当前年份第一天 -获取某月的天数 -获取当月第一天 -获取下月第一天 -获取两日期之间的日期 -格式化时间戳 -时间格式化 -toJSON少8小时问题

/*
 * 获取当前年份的第一天
 */
function getFirstDayOfYear() {
    var date = new Date();
    date.setDate(1);
    date.setMonth(0);
    return date;
}

/*
 * 获取得某月的天数
 * 传当前月值就行 本月11月 就传11 不用减1
 */
function getMonthDays(iYear, iMonth) {
    var monthStartDate = new Date(iYear, iMonth - 1, 1);
    var monthEndDate = new Date(iYear, iMonth, 1);
    var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);//格式转换
    return days;
}

/*
 *  获取当月第一天
 */
function getFirstDayOfMonth() {
    var date = new Date();
    date.setDate(1);
    return date;
}

/*
 *  获取下月第一天
 */
function getFirstDayOfNextMonth(time) {

    var date = new Date(time);
    date.setDate(1);
    date.setMonth(date.getMonth() + 1)
    return date;
}

/*
 * 获取两日期之间的日期
 */
function getdiffdate(stime, etime) {
    //初始化日期列表,数组
    var diffdate = [];
    //开始日期小于等于结束日期,并循环
    while (stime <= etime) {
        //获取开始日期时间戳
        var stime_ts = new Date(stime).getTime();
        var next_date = stime_ts;
        //拼接年月日,这里的月份会返回(0-11),所以要+1
        var next_dates_y = new Date(next_date).getFullYear() + '-';
        var next_dates_m = (new Date(next_date).getMonth() + 1 < 10) ? '0' + (new Date(next_date).getMonth() + 1) + '-' : (new Date(next_date).getMonth() + 1) + '-';
        var next_dates_d = (new Date(next_date).getDate() < 10) ? '0' + new Date(next_date).getDate() : new Date(next_date).getDate();

        //增加一天时间戳后的日期
        stime = stime_ts + (24 * 60 * 60 * 1000);
        diffdate.push(next_dates_y + next_dates_m + next_dates_d);
    }
    return diffdate;
}

  

/**
 * 格式化时间戳
 * @param {any} format
 */
String.prototype.toDate = function (format) {
    var dateMilliseconds;
    if (this.indexOf('-') > -1) {
        return "";
    }
    if (isNaN(this)) {
        //使用正则表达式将日期属性中的非数字(D)删除
        dateMilliseconds = this.replace(/D/igm, "");
    } else {
        dateMilliseconds = this;
    }
    //实例化一个新的日期格式,使用1970 年 1 月 1 日至今的毫秒数为参数
    var date = new Date(parseInt(dateMilliseconds));
    if (date === "Invalid Date") {
        return "";
    }
    var o = {
        "M+": date.getMonth() + 1,                 //月份   
        "d+": date.getDate(),                    //日   
        "H+": date.getHours(),                   //小时   
        "m+": date.getMinutes(),                 //分   
        "s+": date.getSeconds(),                 //秒   
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度   
        "S": date.getMilliseconds()             //毫秒   
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};

/*
 * 时间格式化
 */
Date.prototype.format = function (fmt) {
    var o = {
        "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 k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}

/*
 * 重写时间的toJSON方法,因为在调用JSON.stringify的时候,时间转换就调用的toJSON,这样会导致少8个小时,所以重写它的toJSON方法
 */
Date.prototype.toJSON = function () {
    return this.format("yyyy-MM-dd hh:mm:ss"); // util.formatDate是自定义的个时间格式化函数
}

  

/** * 格式化时间戳 * @param {any} format */String.prototype.toDate = function (format) {    var dateMilliseconds;    if (this.indexOf('-') > -1) {        return "";    }    if (isNaN(this)) {        //使用正则表达式将日期属性中的非数字(D)删除        dateMilliseconds = this.replace(/D/igm, "");    } else {        dateMilliseconds = this;    }    //实例化一个新的日期格式,使用1970 年 1 月 1 日至今的毫秒数为参数    var date = new Date(parseInt(dateMilliseconds));    if (date === "Invalid Date") {        return "";    }    var o = {        "M+": date.getMonth() + 1,                 //月份           "d+": date.getDate(),                    //日           "H+": date.getHours(),                   //小时           "m+": date.getMinutes(),                 //分           "s+": date.getSeconds(),                 //秒           "q+": Math.floor((date.getMonth() + 3) / 3), //季度           "S": date.getMilliseconds()             //毫秒       };    if (/(y+)/.test(format)) {        format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));    }    for (var k in o) {        if (new RegExp("(" + k + ")").test(format)) {            format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));        }    }    return format;};
/* * 时间格式化 */Date.prototype.format = function (fmt) {    var o = {        "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 k in o) {        if (new RegExp("(" + k + ")").test(fmt)) {            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));        }    }    return fmt;}
/* * 重写时间的toJSON方法,因为在调用JSON.stringify的时候,时间转换就调用的toJSON,这样会导致少8个小时,所以重写它的toJSON方法 */Date.prototype.toJSON = function () {    return this.format("yyyy-MM-dd hh:mm:ss"); // util.formatDate是自定义的个时间格式化函数}

原文地址:https://www.cnblogs.com/souphm/p/14950604.html