日期工具类

来源:互联网 发布:mac邮箱软件推荐 编辑:程序博客网 时间:2024/06/08 07:53
import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.GregorianCalendar;public class DateUtil {//将日期格式转换成yyyy-mm-dd格式用于前台显示public static String dateFormatToIE(String date){//如果是null返回""if(date == null || "".equals(date)){return "";}String year = date.substring(0, 4);String month = date.substring(4, 6);String day = date.substring(6, 8);return year+"-"+month+"-"+day;}//将日期格式转换成yyyymmdd格式用于后台数据库存储public static String dateFormatToDB(String date){//如果是null返回""if(date == null || "".equals(date)){return "";}if(date.length()==8){//如果是8位的日期就返回原值return date;}String year = date.substring(0, 4);String month = date.substring(5, 7);String day = date.substring(8, 10);return year+month+day;}//将日期格式转换成查询语句public static String dateFormatToQuerySql(String date,String columnName){String[] dates = date.split("~");if(dates.length==1){String querySql = "AND "+columnName+" LIKE '"+dateFormatToDB(date)+"%' ";return querySql;}else if(dates.length==2){String firstDate = dates[0];String secondDate = dates[1];String querySql = "AND "+columnName+" BETWEEN '"+dateFormatToDB(firstDate)+"' AND '"+dateFormatToDB(secondDate)+"' ";return querySql;}else{throw new RuntimeException("日期参数格式非法");}}public static String getCurDate(String format){SimpleDateFormat sdf = new SimpleDateFormat(format);Date date = new Date();String currDate = sdf.format(date);return currDate;}//获取当前日期后几天的日期86400000为一天的毫秒数public static String getCurDateAfter(Integer num){return getDate(getNow() + (86400000*num));}// 获得当前时间的毫秒表示public static long getNow() {GregorianCalendar now = new GregorianCalendar();return now.getTimeInMillis();}// 根据输入的毫秒数,获得日期字符串private static GregorianCalendar calendar = new GregorianCalendar();// 根据输入的毫秒数,获得日期public static String getDate(long millis) {calendar.setTimeInMillis(millis);return DateFormat.getDateInstance().format(calendar.getTime());}public static int getCountBetweenDates(String beginDate,String endDate,String format) {SimpleDateFormat sd = new SimpleDateFormat(format);long nd = 1000*24*60*60;//一天的毫秒数long diff=0;try {diff = sd.parse(endDate).getTime() - sd.parse(beginDate).getTime();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}int dayCount = (int) (diff/nd);//计算差多少天        return dayCount;}}

0 0