分享一些自己写的性能还算不错的前后端工具函数(推了一些数学公式避免了很多判断以及创建过渡对象的无用步骤)

首先是一些字符串日期相关的工具函数,网上现在很多函数都是直接将字符串转成Date或者LocalDate然后再调类库方法,但这样就有一个多余的创建对象的过程,量小的时候性能 差距不明显,数据量一大就很明显了,所以自己推了一些数学公式,避免掉了一些无用的判断和创建无用对象的步骤,做过相关测试,我的函数要快很多


private String qiantuiDate(String date, int num) {
//将指定日期往前推num月,格式为yyyy-mm
if (StringUtils.isEmpty(date))
throw new RuntimeException("日期不能为空");
String[] split = date.split("-");
int year = Integer.valueOf(split[0]);
int month = Integer.valueOf(split[1]);
int temp = month - num;
if (temp <= 0) {
year -= Math.ceil(num / 12);
month--;
num--;
if (month == 0) {
month = 12;
}
month = 12 - ((num - (num / 12) * 12) - month);
} else {
month = temp;
}
return year + "-" + month;
}


private int getSpaceMonth(String startDate, String endDate) {
//算出两个日期相隔的月份,格式为yyyy-mm
if(StringUtils.isEmpty(startDate)||StringUtils.isEmpty(endDate))
throw new RuntimeException("开始或结束日期不能为空");
String[] startSplit = startDate.split("-");
String[] endSplit = endDate.split("-");
int startYear = Integer.valueOf(startSplit[0]);
int startMonth = Integer.valueOf(startSplit[1]);
int endYear = Integer.valueOf(endSplit[0]);
int endMonth = Integer.valueOf(endSplit[1]);
int month = 0;
int i = endYear - startYear;
if (endYear == startYear) {
month = endMonth - startMonth;
} else if (i >= 1) {
month = 12 - startMonth + endMonth;
if (i > 1)
month += (endYear - startYear - 1) * 12;
}
return month;
}



private String tongbiLocalDate(String date) {
//算出指定日期的同期日期,如2018-06,同期就是2017-06,格式为yyyy-mm
String[] split = date.split("-");
int year = Integer.valueOf(split[0]);
int month = Integer.valueOf(split[1]);
int tempMonth = 12 - month;
year = year - 1;
if (tempMonth == 0) {
month = 12;
} else {
month = 12 - tempMonth;
}
return year + "-" + month;
}

 

 

然后是一些前端的工具类

function formathuanbi(num) {

//保留两位并乘以100,如0.81555就是81,这是为了加上百分号的如:81%
return Math.round(num * 10000) / 100
}

 

 

 

function toThousands(kum) {

//将一个数加上千分位,并保留两位小数,如888666.888,就是888,666.88
kum = kum.toFixed(2);
var num = (kum || 0).toString(), result = '';
while (num.length > 3) {
result = ',' + num.slice(-3) + result;
num = num.slice(0, num.length - 3);
}
if (num) {
result = num + result;
}
var str = result.split(',');
var b = "";
for (var i = 0; i < str.length; i++) {
if (i < str.length - 2) {
b += str[i] + ",";
} else {
b += str[i]
}
}
if (b[0] == '-' && b[1] == ',') {
b = b.replace(",", "");
}
return b;
}

posted on 2018-08-24 12:06  羊飞  阅读(411)  评论(0编辑  收藏  举报

导航