Java-常用工具方法

一 Json转换

1 输出组装好的json

ObjectMapper mapper = new ObjectMapper();
try {
String requiredJson = mapper.writeValueAsString(query);
System.out.println("---------------");
System.out.println(requiredJson);
System.out.println("---------------");
} catch (JsonProcessingException e) {
e.printStackTrace();
}

2 将对象转换成为字符串

String str = JSON.toJSONString(infoDo);
3 将字符串转换成为对象

InfoDo infoDo = JSON.parseObject(strInfoDo, InfoDo.class);
4 将对象集合转换成为字符串

String users = JSON.toJSONString(users);
5 将字符串转换成为对象集合

List<User> userList = JSON.parseArray(userStr, User.class);

二 字符串处理

1 将rawString从startString开始截取至endString

public static List<String> getOneMatchString(String rawString, String startString, String endString) {
String tempString = rawString;
int startPos=0;
int endPos=0;
List<String> result = new ArrayList<>();

startPos=startString.length()+tempString.indexOf(startString);
while ((startPos-startString.length())!= -1){
endPos=tempString.indexOf(endString);
if(endPos>startPos){
result.add(tempString.substring(startPos,endPos));
}
tempString=tempString.substring(endPos+endString.length());
startPos=startString.length()+tempString.indexOf(startString);
}
return result;
}
2 转化为百分比格式字符串
public static String toRate(String n){
try {
String rate = String.format("%.2f", (Double.parseDouble(n) * 100)) + "%";
return rate;
}catch (Exception e){
e.printStackTrace();
return "0.00%";
}
}
3 保留两位小数
public static String formatTwoNumber(String n){
try {
String rate = String.format("%.2f", Double.parseDouble(n));
return rate;
}catch (Exception e){
e.printStackTrace();
return "0.00";
}
}
三 mybatis常用语句

1 mybatis新增记录后返回id

扫描二维码关注公众号,回复: 5450778 查看本文章

<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>

2 模糊匹配

<if test="keyword != null and keyword != ''">
and message_content like CONCAT('%','${keyword}','%')
</if>

3 日期筛选

<if test="startDate !=null  and startDate!=''">
and DATE_FORMAT(create_time , '%Y-%m-%d') >= DATE_FORMAT(#{startDate} , '%Y-%m-%d')
</if>
<if test="endDate !=null and endDate!=''">
and DATE_FORMAT(create_time , '%Y-%m-%d') &lt;= DATE_FORMAT(#{endDate} , '%Y-%m-%d')
</if>

 4 选择结构

<if test="category1 != null and category1 != 0">
<choose>
<when test="category2 != null and category2 != 0">
and ae.category1 = #{category1} and ae.category2 = #{category2}
</when>
<otherwise>
and ae.category1 = #{category1}
</otherwise>
</choose>
</if>

 5 循环结构

   id in

<foreach collection="list" separator="," open="(" close=")" item="item">
#{item.id}
</foreach>

 四 日期格式化与处理

获取昨天的日期 格式:"yyyy-MM-dd"

public static String getYesterday(){
Date dNow = new Date();
Calendar calendar = Calendar.getInstance();
//得到前一天的时间
calendar.add(Calendar.DAY_OF_MONTH, -1);
Date dBefore = calendar.getTime();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
//格式化当前时间
return sdf.format(dBefore);
}
2 获取n前的日期 格式:"yyyy-MM-dd"
public static String getPastNdays(Integer n){
Date dNow = new Date();
Calendar calendar = Calendar.getInstance();
//得到前n天的时间
calendar.add(Calendar.DAY_OF_MONTH, n-2*n);
Date dBefore = calendar.getTime();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
//格式化当前时间
return sdf.format(dBefore);
}
3 得到指定日期n天前的日期 格式:"yyyy-MM-dd"
public static String getPastNdays(Date date,Integer n) throws ParseException {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
//得到前n天的时间
calendar.add(Calendar.DAY_OF_MONTH, n-2*n);
Date dBefore = calendar.getTime();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
//格式化当前时间
return sdf.format(dBefore);
}
public static String getPastNdays(String date,Integer n) {
Calendar calendar = Calendar.getInstance();
try {
calendar.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
calendar.add(Calendar.DAY_OF_MONTH, n-2*n);
Date dBefore = calendar.getTime();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(dBefore);
}
4 得到指定日期前一天的日期
public static String getYesterday(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, -1);
Date dBefore = calendar.getTime();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(dBefore);
}
public static String getYesterday(String date){
Calendar calendar = Calendar.getInstance();
try {
calendar.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
calendar.add(Calendar.DAY_OF_MONTH, -1);
Date dBefore = calendar.getTime();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(dBefore);
}
5 将短时间格式时间转换为字符串 yyyy-MM-dd
public static String dateToStr(Date dateDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String dateString = formatter.format(dateDate);
return dateString;
}
6 将短时间格式字符串转换为时间 yyyy-MM-dd

public static Date strToDate(String strDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}

7 将短时间格式字符串转换为时间 yyyy-mm-dd hh:mm:ss

public static Date strToDates(String strDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}
8 日期字符串转换为指定格式的日期
public static Date strToDate(String strDate,String formate) {
SimpleDateFormat formatter = new SimpleDateFormat(formate);
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}
9 获取当前时间
public static String getNow() {
Date date=new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String datetime = formatter.format(date);
return datetime;
}
10 获取某段时间内的所有日期

public static List<String> findDates(String begin, String end) {
Date dBegin=DateUtils.strToDate(begin);
Date dEnd=DateUtils.strToDate(end);
List<String> lDate = new ArrayList();
lDate.add(begin);
Calendar calBegin = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
calBegin.setTime(dBegin);
Calendar calEnd = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
calEnd.setTime(dEnd);
// 测试此日期是否在指定日期之后
while (dEnd.after(calBegin.getTime())) {
// 根据日历的规则,为给定的日历字段添加或减去指定的时间量
calBegin.add(Calendar.DAY_OF_MONTH, 1);
Date time = calBegin.getTime();
lDate.add(DateUtils.dateToStr(time));
}
return lDate;
}
11 根据日期获取当前是星期几

public static Integer getWeekByDate(String date){
Calendar calendar = Calendar.getInstance();
Date d = strToDate(date);
calendar.setTime(d);
SimpleDateFormat format = new SimpleDateFormat("E");
String s = format.format(calendar.getTime());
int n = 0;
if(s.contains("一")){
n = 1;
}else if(s.contains("二")){
n = 2;
}else if(s.contains("三")){
n = 3;
}else if(s.contains("四")){
n = 4;
}else if(s.contains("五")){
n = 5;
}else if(s.contains("六")){
n = 6;
}else if(s.contains("日")){
n = 7;
}
return n;
}
12 计算从startTime-endTime有多少天
public static int days(String startTime,String endTime){
int days = 0;
try {
Date end = new SimpleDateFormat("yyyy-MM-dd").parse(endTime);
Date start = new SimpleDateFormat("yyyy-MM-dd").parse(startTime);
long n = ( (end.getTime()-start.getTime())/(24*60*60*1000) ) + 1;
days = Integer.parseInt(n+"");
} catch (ParseException e) {
e.printStackTrace();
return days;
}
return days;
}
13 获取两个日期之间的每个星期的起始日期
public static List<Map<String,String>> getWeekList (String startTime, String endTime){
List<Map<String,String>> weeks = new ArrayList<>();
int sub = days(startTime,endTime);
if(sub<=7){
Map<String,String> firstWeek = new HashMap<>();
firstWeek.put("startTime",startTime);
firstWeek.put("endTime",endTime);
weeks.add(firstWeek);
}else {
int startWeek = getWeekByDate(startTime);
int week = 7 - startWeek;
Map<String,String> firstWeek = new HashMap<>();
firstWeek.put("startTime",startTime);
String weekSeven = getDateByAfter(startTime,week);
firstWeek.put("endTime",weekSeven);
weeks.add(firstWeek);
sub = sub - week;
String sunday = weekSeven;
while(sub >= 7){
Map<String,String> weeki = new HashMap<>();
String start = getDateByAfter(sunday,1);
weeki.put("startTime",start);
sunday = getDateByAfter(start,6);
weeki.put("endTime",sunday);
weeks.add(weeki);
sub = sub - 7;
}
if(sub != 0){
Map<String,String> weekEnd = new HashMap<>();
String start = getDateByAfter(sunday,1);
weekEnd.put("startTime",start);
weekEnd.put("endTime",endTime);
weeks.add(weekEnd);
}
}
return weeks;
}
14 获取两个日期之间的每个月的起始日期
public static List<Map<String,String>> getMonthList(String startTime,String endTime){
String startMonth = startTime.substring(5,7);
String endMonth = endTime.substring(5,7);
List<Map<String,String>> result = new ArrayList<>();
if(startMonth.equals(endMonth)){
Map<String,String> onlyMonth = new HashMap<>();
onlyMonth.put("startTime",startTime);
onlyMonth.put("endTime",endTime);
result.add(onlyMonth);
}else {
String nextStartTime = startTime;
do{
Map<String,String> monthi = new HashMap<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar lastDate = Calendar.getInstance();
try {
lastDate.setTime(sdf.parse(nextStartTime));
} catch (ParseException e) {
e.printStackTrace();
}
monthi.put("startTime",nextStartTime);
// 设置为这个月的第 1 天
lastDate.set(Calendar.DATE, 1);
lastDate.add(Calendar.MONTH, 1);
nextStartTime = sdf.format(lastDate.getTime());
lastDate.add(Calendar.DATE, -1);
String format = sdf.format(lastDate.getTime());
monthi.put("endTime",format);
result.add(monthi);
startMonth = nextStartTime.substring(5,7);
}while(!startMonth.equals(endMonth));
Map<String,String> lastMonth = new HashMap<>();
String lastMonthStart = endTime.substring(0,8)+"01";
lastMonth.put("startTime",lastMonthStart);
lastMonth.put("endTime",endTime);
result.add(lastMonth);
}
return result;
}
15 获取两个日期之间的所有日期
public static List<String> getDays(String startTime, String endTime) {
List<String> days = new ArrayList<String>();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date start = dateFormat.parse(startTime);
Date end = dateFormat.parse(endTime);
Calendar tempStart = Calendar.getInstance();
tempStart.setTime(start);
Calendar tempEnd = Calendar.getInstance();
tempEnd.setTime(end);
// 日期加1(包含结束)
tempEnd.add(Calendar.DATE, +1);
while (tempStart.before(tempEnd)) {
days.add(dateFormat.format(tempStart.getTime()));
tempStart.add(Calendar.DAY_OF_YEAR, 1);
}
} catch (ParseException e) {
e.printStackTrace();
}
return days;
}
五 浮点数运算
public class ArithUtils{
//默认除法运算精度
private static final int DEF_DIV_SCALE = 10;
//这个类不能实例化
private ArithUtils(){
}
/**
* 提供精确的加法运算。
* @param v1 被加数
* @param v2 加数
* @return 两个参数的和
*/
public static double add(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}
/**
* 提供精确的减法运算。
* @param v1 被减数
* @param v2 减数
* @return 两个参数的差
*/
public static double sub(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}
/**
* 提供精确的乘法运算。
* @param v1 被乘数
* @param v2 乘数
* @return 两个参数的积
*/
public static int mul(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).setScale(0,BigDecimal.ROUND_HALF_UP).intValue();
}

/**
* 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到
* 小数点以后10位,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @return 两个参数的商
*/
public static double div(double v1,double v2){
return div(v1,v2,DEF_DIV_SCALE);
}

/**
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指
* 定精度,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @param scale 表示表示需要精确到小数点以后几位。
* @return 两个参数的商
*/
public static double div(double v1,double v2,int scale){
if(scale<0){
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
if(v2==0){
return 0;
}
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
}

/**
* 提供精确的小数位四舍五入处理。
* @param v 需要四舍五入的数字
* @param scale 小数点后保留几位
* @return 四舍五入后的结果
*/
public static double round(double v,int scale){
if(scale<0){
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
BigDecimal result=b.divide(one,scale,BigDecimal.ROUND_HALF_UP);
return result.doubleValue();
}

public static String roundString(double v,int scale){
if(scale<0){
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one,scale,BigDecimal.ROUND_HALF_UP).toString();
}

public static BigDecimal roundBigDecimal(double v,int scale){
if(scale<0){
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one,scale,BigDecimal.ROUND_HALF_UP);

}
/**
* @Description: 根据type决定向上还是取整,还是四舍五入
* @author: zw
*/
public static double round(double v,int scale,int type){
if(scale<0){
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one,scale,type).doubleValue();
}
/**
* @Description: 对double类型最多保留9位
* @author: zw
*/
public static double doubleLen(double v,int len){
DecimalFormat df = new DecimalFormat("######0.000000000");
String format = df.format(v);

//保留位数,本来长度<目标长度,直接返回
if(format.length()<=len){
return v;
}
String sub=format.substring(0,len+1);
Double val=Double.parseDouble(sub);
String[] split = sub.split(".");
if(split.length>=2){
int scale=split[1].length();
val=ArithUtils.round(val, scale);
}
return val;
}

/**
* 将获取的小数转换为整数
*/
public static Long doubleParseLong(String doubleStr){
Long result = null;
try {
result = Double.valueOf(doubleStr).longValue();
return result;
}catch (Exception e){
e.printStackTrace();
return 0L;
}
}
}
 


 

猜你喜欢

转载自www.cnblogs.com/serena25/p/10488693.html