JS 日期转换,格式化等常用的函数定义

//判断字符串是否日期格式
        function isDate(val) {
            return new Date(val) != "Invalid Date";
        }
        //日期格式化
        function formatDate2(val) {
            return formatDate(val, 'yyyy-MM-dd');
        }
        //日期格式化
        function formatDateTime(val) {
            return formatDate(val, 'yyyy-MM-dd hh:mm:ss');
        }
        //数字格式化
        function formatNumber(val) {
            if (val != '') {
                val = val.toFixed(0);
            }
            return formatWithThousandsSeparator(val);
        }
        //数字格式化
        function formatNumber2(val) {
            if (val != '') {
                val = val.toFixed(2);
            }
            return formatWithThousandsSeparator(val);
        }
        //数字格式化
        function formatNumber4(val) {
            if (val != '') {
                val = val.toFixed(4);
            }
            return formatWithThousandsSeparator(val);
        }


function formatDate(datestring, formatstring) {
    if (formatstring == undefined) {
        formatstring = 'yyyy-MM-dd';
    }

    if (datestring == null || datestring == '/Date(-62135596800000)/' || datestring.length <= 0) {
        return '';
    }
    else {
        var dateint = parseInt(datestring.substr(6));
        return (new Date(dateint)).format(formatstring);
    }
}

//将数字转换成带千位分隔符
function formatWithThousandsSeparator(s) {
    if (/[^0-9\.]/.test(s)) return s;
    try {
        s = String(s);
        s = s.replace(/^(\d*)$/, "$1.");
        s = (s + "&end").replace(/(\d*\.\d*)\d*/, "$1");
        s = s.replace(".", ",");
        var re = /(\d)(\d{3},)/;
        while (re.test(s))
            s = s.replace(re, "$1,$2");

        s = s.replace(/,(\d*)&end$/, ".$1");

        if (s.substring(s.length - 1, s.length) == '.')
            s = s.substring(0, s.length - 1);
    } catch (e)
            { }
    return s;
}

利用上面的方法,对于后台传到前台的数字类型的datetime数据,直接

var expectedSendTime = rowData.ExpectedSendTime;
$(cell).html(formatDate2(expectedSendTime));

就可以得到对应的日期格式字符,很方便!

posted on 2018-12-07 11:54  itjeff  阅读(2323)  评论(0编辑  收藏  举报

导航