您的位置:首页 > Web前端 > JavaScript

【工作笔记】js常用方法--格式化时间、格式化金额

2017-10-17 18:09 621 查看
// 格式化时间
function formatTime (time){
var format = "yyyy-MM-dd HH:mm:ss";
var t = new Date(time);
var tf = function(i){return (i < 10 ? '0' : '') + i};
return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a){
switch(a){
case 'yyyy':
return tf(t.getFullYear());
break;
case 'MM':
return tf(t.getMonth() + 1);
break;
case 'mm':
return tf(t.getMinutes());
break;
case 'dd':
return tf(t.getDate());
break;
case 'HH':
return tf(t.getHours());
break;
case 'ss':
return tf(t.getSeconds());
break;
}
})
}


/**
* 金额格式化
*/
function formatCurrencyFen(num) {
num = num / 100;
num = num.toString().replace(/\$|\,/g, '');
if (isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num * 100 + 0.50000000001);
cents = num % 100;
num = Math.floor(num / 100).toString();
if (cents < 10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
num = num.substring(0, num.length - (4 * i + 3)) + ','
+ num.substring(num.length - (4 * i + 3));
return (((sign) ? '' : '-') + num + '.' + cents);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  常用方法