前端 jquery 日期正则校验,时间戳转换,及给定日期格式转换日期代码

日期正则校验:前后端都适用,有平年、闰年校验之分,也兼顾yyyyMMdd、yyyy-MM-dd、yyyy/MM/dd 格式

String DATAREG = "^(?:(?!0000)[0-9]{4}([-/.]?)(?:(?:0?[1-9]|1[0-2])([-/.]?)(?:0?[1-9]|1[0-9]|2[0-8])|(?:0?[13-9]|1[0-2])([-/.]?)(?:29|30)|(?:0?[13578]|1[02])([-/.]?)31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)([-/.]?)0?2([-/.]?)29)$";

时间戳转换为年月日时分秒:yyyy-MM-dd HH:MM:SS

var curr_time = new Date(data.time);
var year = curr_time.getFullYear();
var month = curr_time.getMonth() + 1 < 10 ? '0' + (curr_time.getMonth() + 1) : curr_time.getMonth() + 1;
var day = curr_time.getDate() < 10 ? '0' + curr_time.getDate() : curr_time.getDate();
var time1 = year + "-" + month + "-" + day + " " + curr_time.getHours() + ":" + curr_time.getMinutes() + ":" + curr_time.getSeconds();

console.log(time1);

给定日期格式转换日期:(转载 //author: meizz)

Date.prototype.Format = function(fmt) { //fmt:yyyy-MM-dd hh:mm:ss(实参)
    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;
}

猜你喜欢

转载自blog.csdn.net/yang1076180972/article/details/82993979
今日推荐