你好,js中Date类没有直接格式化的方法,所以需要自己写,你只需将下列代码在格式化前加入,即可使用。代码摘自http://www.jb51.net/article/22657.htm。使用方法如下:new Date().format('yyyyMMdd')
Date.prototype.format = function(format){var o = {
"M+" : this.getMonth()+1, //month
"d+" : this.getDate(), //day
"h+" : this.getHours(), //hour
"m+" : this.getMinutes(), //minute
"s+" : this.getSeconds(), //second
"q+" : Math.floor((this.getMonth()+3)/3), //quarter
"S" : this.getMilliseconds() //millisecond
}
if(/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length))
}
for(var k in o) {
if(new RegExp("("+ k +")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length))
}
}
return format
}
1、如果变量是字符串则js的加号便会把两个及多个字符串拼接成一个。
2、为了让js能够对变量的数据进行加或者其他运算则可用parseInt来把字符串变为整数。
3、如果是包含有小点的字符串在用parseInt转换时会直接把小点后面的数字忽略掉滴。也就是直接取整数而不是四舍五入计算。
4、所以对于有小点的字符串便可以用parseFloat来转换。
5、所以便可以用toFixed()来保留小数的位数。
6、这样JS便可以得到两数运算比较精确的数字结果了。