JS Date parse

 

因为JS中的Date转换格式没有“-”这种间隔符,Date.parse会生成NAN,所以只能进行转换。

<script type="text/javascript">
    function changeWeddingTime() {
        var dt= TimeSeparatorReplace(marry_time.value);
        $(wedding_date).html(dt.Format("yyyy/MM/dd"));
        var time = dt.Format("hh:mm");
        var hour = dt.Format("h");
        if (parseInt(hour) >= 12) {
            $(wedding_time).html(time + " " + "PM");
        } else {
            $(wedding_time).html(time + " " + "AM");
        }
    }
</script>

 扩展的方法

Date.prototype.Format = function (fmt) { //author: meizz   
    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": DataPrivatePad(this.getMilliseconds(), 3)             //毫秒   
    };
    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;
}

function DataPrivatePad(num, n) {
    return (Array(n).join(0) + num).slice(-n);
}

///将"-"换成"/"
function TimeSeparatorReplace(str) {
    var regEx = new RegExp("\\-", "gi");
    str = str.replace(regEx, "/");
    if (!isNaN(Date.parse(str))) {
        return new Date(str);
    } else {
        return new Date();//如果失败就直接给个当前的时间好了
    }
}

 

posted @ 2016-04-19 12:43  Danlis  阅读(789)  评论(0编辑  收藏  举报