/** * 输入Date 和 + - 数字代表天数 进行计算出需要的Date * @param date * @param day * @return * @throws ParseException */ public static Date addDate(Date date, long day) throws ParseException { long time = date.getTime(); // 得到指定日期的毫秒数 day = day * 24 * 60 * 60 * 1000; // 要加上的天数转换成毫秒数 time += day; // 相加得到新的毫秒数 // time -= day; // 相减得到新的毫秒数 return new Date(time); // 将毫秒数转换成日期 }
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 日期格式 Date start = null; Date end = null; if (!e.isEmpty()||!s.isEmpty()){ start = dateFormat.parse(s); end = dateFormat.parse(e); }
两个搭配使用,判断两个Date时间相距的年份,给个小例子
hotLawyer.setTime("执业"+yearCompare(lawyerDO.getMajor(),new Date())+"年");
/** * 计算2个日期之间相差的 相差多少年月日 * 比如:2011-02-02 到 2017-03-02 相差 6年,1个月,0天 * @param fromDate * @param toDate * @return */ public static DayCompare dayComparePrecise(Date fromDate, Date toDate){ Calendar from = Calendar.getInstance(); from.setTime(fromDate); Calendar to = Calendar.getInstance(); to.setTime(toDate); int fromYear = from.get(Calendar.YEAR); int fromMonth = from.get(Calendar.MONTH); int fromDay = from.get(Calendar.DAY_OF_MONTH); int toYear = to.get(Calendar.YEAR); int toMonth = to.get(Calendar.MONTH); int toDay = to.get(Calendar.DAY_OF_MONTH); int year = toYear - fromYear; int month = toMonth - fromMonth; int day = toDay - fromDay; DayCompare dayCompare = new DayCompare(); dayCompare.setDay(day); dayCompare.setMonth(month); dayCompare.setYear(year); return dayCompare; } public static String yearCompare(Date fromDate,Date toDate){ DayCompare result = dayComparePrecise(fromDate, toDate); double month = result.getMonth(); double year = result.getYear(); //返回2位小数,并且四舍五入 DecimalFormat df = new DecimalFormat("######0"); return df.format(year + month / 12); }
这个就是一个简单的时间类
public class DayCompare { private int year; private int month; private int day; public int getYear() { return year; } public void setYear(int year) { this.year = year; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public int getDay() { return day; } public void setDay(int day) { this.day = day; } }
转载如下,如果链接没有失效,也欢迎去原作者博文看。
立即前往
本文作者为DBC,转载请注明。