JavaScript常用工具方法

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/An1090239782/article/details/102580347

1、日期格式化

/**
 * 日期格式化
 * 格式:yyyy-MM-dd hh:mm:ss
 */
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;
};

2、将日期字符串转换为Date,字符串格式为(yyyy-mm-dd hh:mm:ss)

/**
 * 将日期字符串转换为Date,字符串格式为(yyyy-mm-dd hh:mm:ss)
 */
function dateConversion(dateStr) {
    // 去掉毫秒数
    if (dateStr.indexOf(".") > 0) {
        dateStr = dateStr.substring(0, dateStr.indexOf("."));
    }
    var regExp = new RegExp("\\-", "gi");
    return new Date(dateStr.replace(regExp, "/"));
}

3、JS获取当天00:00:00时间和23:59:59的时间

/**
 * JS获取当天00:00:00时间和23:59:59的时间
 */
function getTodayBeginEndTime(callback) {
    var d = new Date();   // 程序计时的月从0开始取值后+1
    var year = d.getFullYear();
    var mouth = d.getMonth() + 1;
    var day = d.getDate();
    if (mouth <= 9) {
        mouth = "0" + mouth
    }
    if (day <= 9) {
        day = "0" + day
    }
    var beginTime = year + "-" + mouth + "-"
        + day + " 00:00:00";
    var endTime = year + "-" + mouth + "-"
        + day + " 23:59:59";
    callback(beginTime, endTime)
}

猜你喜欢

转载自blog.csdn.net/An1090239782/article/details/102580347