package com.whyc.util; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; import org.springframework.context.ApplicationContext; import org.springframework.web.context.ContextLoader; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.*; import java.lang.reflect.Type; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class ActionUtil{ public static String time_yyyyMMddHHmmss = "yyyy-MM-dd HH:mm:ss"; /* * 获取HttpServletRequest */ public static HttpServletRequest getRequest(){ ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = requestAttributes.getRequest(); return request; } /* * 获取HttpServletResponse */ public static HttpServletResponse getResponse(){ ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletResponse response = requestAttributes.getResponse(); return response; } /* * 获取HttpSession */ public static HttpSession getSession(){ return getRequest().getSession(); } /** * * @return 返回application */ public static ServletContext getApplication(){ ApplicationContext currentWebApplicationContext = ContextLoader.getCurrentWebApplicationContext(); ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext(); return servletContext; } //获取application中互斥上传的标志位flag public static int getFlag(){ ServletContext app=getApplication(); int flag=(Integer) app.getAttribute("flag"); return flag; } ////给application中互斥上传的标志位flag设置值 public static void setFlag(int flag){ ServletContext app=getApplication(); app.setAttribute("flag", flag); } /* * 获取将对象转换成json格式 */ public static String tojson(Object obj){ Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); return gson.toJson(obj); } public static String chageDateToString(Date time,String type){ String msg = ""; SimpleDateFormat sdf = new SimpleDateFormat(type); msg = sdf.format(time); return msg; } /** * * @param datetype 需要解析的日期的格式如:"yyyy-MM-dd HH:mm:ss" * @return 得到对应的gson对象 */ public static Gson getGson(String datetype){ return new GsonBuilder().setDateFormat(datetype).create(); } /** * 获取默认的gson对象 * @return */ public static Gson getGson(){ return new Gson(); } public static T getObject(String jsonstring,Type listtype){ Gson gson=new Gson(); T t=null; try { t=gson.fromJson(jsonstring, listtype); } catch (JsonSyntaxException e) { e.printStackTrace(); } return t; } /** * * @return 获取输出流 */ public static PrintWriter getOut(){ PrintWriter out =null; try { out=getResponse().getWriter(); } catch (IOException e) { e.printStackTrace(); } return out; } /** * * @param time java.util包中的时间 * @return java.sql时间 */ public static Date getSimpDate(Date time){ //System.out.println(time); return new java.sql.Date(time.getTime()); } //使用MD5加密 /*public static Object EncryptionMD5(Object obj){ String md5=null; if(obj!=null && obj.toString().length()>0){ md5=DigestUtils.md5Hex(obj.toString()); } return md5; }*/ //使用Base64加密 public static Object EncryptionBase64(Object obj){ String base64=null; if(obj!=null && obj.toString().length()>0){ base64=new BASE64Encoder().encode(obj.toString().getBytes()); base64 = base64.replaceAll("[\\s*\t\n\r]", ""); //替换加密后不换行 } return base64; } //使用Base64解密 public static Object DecryptionBase64(Object obj){ String base64=null; if(obj!=null && obj.toString().length()>0){ try { base64 = new String(new BASE64Decoder().decodeBuffer(obj.toString())); } catch (IOException e) { e.printStackTrace(); } } return base64; } //获取指定年月的天数 public static int getDaysByYearMonth(int year, int month) { Calendar a = Calendar.getInstance(); a.set(Calendar.YEAR, year); a.set(Calendar.MONTH, month - 1); a.set(Calendar.DATE, 1); a.roll(Calendar.DATE, -1); int maxDate = a.get(Calendar.DATE); return maxDate; } /** * * @return 获取当前session 中的用户对象 */ /*public static Object getUser(){ HttpSession session =getSession(); Object obj=session.getAttribute("user"); User_inf user_inf = new User_inf(); if(obj==null){ user_inf.setUName("superuser"); user_inf.setUId(1002); }else{ user_inf=(User_inf) session.getAttribute("user"); } return user_inf; }*/ //获取某年某月的起始和结束时间 //需要注意的是:月份是从0开始的,比如说如果输入5的话,实际上显示的是4月份的最后一天,千万不要搞错了哦 public static String getLastDayOfMonth(int year, int month) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month); cal.set(Calendar.DAY_OF_MONTH,cal.getActualMaximum(Calendar.DATE)); return new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime())+"23:59:59"; } public static String getFirstDayOfMonth(int year, int month) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month); cal.set(Calendar.DAY_OF_MONTH,cal.getMinimum(Calendar.DATE)); return new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime())+"00:00:00"; } //获取当前时间的年份 public static int getNowYear(){ Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 ca.setTime(new Date()); //设置时间为当前时间 int year = ca.get(Calendar.YEAR); //System.out.println(month); return year; } //获取当前时间的月份 public static int getNowMonth(){ Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 ca.setTime(new Date()); //设置时间为当前时间 int month = ca.get(Calendar.MONTH) + 1; //System.out.println(month); return month; } //获取当前时间的日期 public static int getNowday(){ Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 ca.setTime(new Date()); //设置时间为当前时间 int day = ca.get(Calendar.DAY_OF_MONTH); //System.out.println(month); return day; } //当前时间加上x小时 public static String getDateAdd(int minute){ Date date = new Date(); Calendar c = Calendar.getInstance(); c.setTime(date); c.add(Calendar.MINUTE, minute); return new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss").format(c.getTime()); } //获取时间的年份 public static int getDateYear(Date date){ Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 ca.setTime(date); //设置时间为当前时间 int year = ca.get(Calendar.YEAR); //System.out.println(month); return year; } //获取时间的月份 public static int getDateMonth(Date date){ Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 ca.setTime(date); //设置时间为当前时间 int month = ca.get(Calendar.MONTH) + 1; //System.out.println(month); return month; } //获取时间的日期 public static int getDateday(Date date){ Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 ca.setTime(date); //设置时间为当前时间 int day = ca.get(Calendar.DAY_OF_MONTH); //System.out.println(month); return day; } //当前时间加上x小时 public static Date getDateAdd(Date date,int minute){ Calendar c = Calendar.getInstance(); c.setTime(date); c.add(Calendar.MINUTE, minute); return c.getTime(); } //给定时间判断与当前时间相比是否为老电池(numYear为时间期限几年) public static int judgeBatt(Date inUseDate,Date date,int numYear){ int judge=0; inUseDate.setYear(ActionUtil.getDateYear(inUseDate)+numYear-1900); //System.out.println("inUseDate: "+inUseDate); if(inUseDate.after(date)){ judge=1; }else{ judge=0; } return judge; } //获取某年某月某日内的时间 public static Date getWorkDay(Date date,Date noticeTime) { Calendar cal = Calendar.getInstance(); cal.setTime(date); //设置时间为执行日期 int year = cal.get(Calendar.YEAR);//年 int month = cal.get(Calendar.MONTH);//月 int day = cal.get(Calendar.DAY_OF_MONTH);//日 cal.setTime(noticeTime);//设置时间为提醒时间段 /*int hour=cal.get(Calendar.HOUR_OF_DAY);//时 int minute=cal.get(Calendar.MINUTE);//分 int second=cal.get(Calendar.SECOND);//秒*/ cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month); cal.set(Calendar.DAY_OF_MONTH,day); return cal.getTime(); } //获取某年某月某日起始时间/结束时间 public static String getDayTime(int year, int month,int day,int type) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month); cal.set(Calendar.DAY_OF_MONTH,day); if(type==1){ return new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime())+"00:00:00"; } else if(type==2){ return new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime())+"09:00:00"; }else if(type==3){ return new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime())+"17:00:00"; }else if(type==4){ return new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime())+"23:59:59"; } return new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime()); } //计算电池使用了多少个月 public static int battInuseMonth(Date inUseDate){ int useDay=0; Date nowd=new Date();//当前时间 int inuseY=ActionUtil.getDateYear(inUseDate); int inuseM=ActionUtil.getDateMonth(inUseDate); int nowY=ActionUtil.getDateYear(nowd); int nowM=ActionUtil.getDateMonth(nowd); if(inuseY==nowY){ useDay=nowM-inuseM; }else{ useDay=(nowY-inuseY)*12+nowM-inuseM; } return useDay; } //计算日期之间相差的天数 public static int daysBetween(Date smdate,Date bdate) { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); try { smdate=sdf.parse(sdf.format(smdate)); bdate=sdf.parse(sdf.format(bdate)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } Calendar cal = Calendar.getInstance(); cal.setTime(smdate); long time1 = cal.getTimeInMillis(); cal.setTime(bdate); long time2 = cal.getTimeInMillis(); long between_days=(time2-time1)/(1000*3600*24); return Math.abs(Integer.parseInt(String.valueOf(between_days))); } //计算日期之间相差的小时 public static int HoursBetween(Date smdate,Date bdate) { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { smdate=sdf.parse(sdf.format(smdate)); bdate=sdf.parse(sdf.format(bdate)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } Calendar cal = Calendar.getInstance(); cal.setTime(smdate); long time1 = cal.getTimeInMillis(); cal.setTime(bdate); long time2 = cal.getTimeInMillis(); long between_hours=(time2-time1)/(1000*3600); //System.out.println("between_hours:"+between_hours); return (int) Math.abs(between_hours); } //比较两个时间的大小 public static int compareDate(Date d1,Date d2){ if (d1.getTime() > d2.getTime()) { return 1; } else if (d1.getTime() < d2.getTime()) { return -1; } else {//相等 return 0; } } /** * @Description: 根据图片地址转换为base64编码字符串 * @Author: * @CreateTime: * @return */ public static String getImageStr(String imgFile) { InputStream inputStream = null; byte[] data = null; try { inputStream = new FileInputStream(imgFile); data = new byte[inputStream.available()]; inputStream.read(data); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } // 加密 BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data); } /** * @Description: 将base64编码字符串转换为图片 * @Author: * @CreateTime: * @param imgStr base64编码字符串 * @param path 图片路径-具体到文件 * @return */ public static boolean generateImage(String imgStr, String path) { if (imgStr == null) return false; BASE64Decoder decoder = new BASE64Decoder(); try { // 解密 byte[] b = decoder.decodeBuffer(imgStr); // 处理数据 for (int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } OutputStream out = new FileOutputStream(path); out.write(b); out.flush(); out.close(); return true; } catch (Exception e) { return false; } } /** * 将输入流中的数据读到字节数组中 * @param is * @return */ public static byte[] IStoByteArr(InputStream is){ byte[] b = null; try { b = new byte[is.available()]; is.read(b); } catch (IOException e) { e.printStackTrace(); } finally{ if(is != null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } return b; } /** * 创建指定的文件文件,若不存在则先创建指定的文件夹再创建指定的文件 * @param filePath */ public static void createFilefolderIFNotExist(String filePath){ File f = new File(filePath); if(!f.exists()){ if(!f.getParentFile().exists()){ f.getParentFile().mkdirs(); } } } }