JS 日期轉換,格式化等常用的函式定義
阿新 • • 發佈:2018-12-07
//判斷字串是否日期格式 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));
就可以得到對應的日期格式字元,很方便!