在Java開發物流或是其他功能的時候會用到兩個日期相差多天的資料,所以整理了一下備用。
調用方式:
| 代碼如下 |
複製代碼 |
long date1 = getDateTime("20121201");//可改成自己的日期類型,但以“20121212”這種格式 long date2 = getDateTime("20121212"); int day = dateInterval(date1, date2); System.out.println(day); |
具體實現方法調用:
| 代碼如下 |
複製代碼 |
/** * 計算出兩個日期之間相差的天數 * 建議date1 大於 date2 這樣計算的值為正數 * @param date1 日期1 * @param date2 日期2 * @return date1 - date2 */ public static int dateInterval(long date1, long date2) { if(date2 > date1){ date2 = date2 + date1; date1 = date2 - date1; date2 = date2 - date1; } // Canlendar 該類是一個抽象類別 // 提供了豐富的日曆欄位 // 本程式中使用到了 // Calendar.YEAR 日期中的年份 // Calendar.DAY_OF_YEAR 當前年中的天數 // getActualMaximum(Calendar.DAY_OF_YEAR) 返回今年是 365 天還是366天 Calendar calendar1 = Calendar.getInstance(); // 獲得一個日曆 calendar1.setTimeInMillis(date1); // 用給定的 long 值設定此 Calendar 的目前時間值。 Calendar calendar2 = Calendar.getInstance(); calendar2.setTimeInMillis(date2); // 先判斷是否同年 int y1 = calendar1.get(Calendar.YEAR); int y2 = calendar2.get(Calendar.YEAR); int d1 = calendar1.get(Calendar.DAY_OF_YEAR); int d2 = calendar2.get(Calendar.DAY_OF_YEAR); int maxDays = 0; int day = 0; if(y1 - y2 > 0){ day = numerical(maxDays, d1, d2, y1, y2, calendar2); }else{ day = d1 - d2; } return day; } /** * 日期間隔計算 * 計算公式(樣本): * 20121201- 20121212 * 取出20121201這一年過了多少天 d1 = 天數 取出20121212這一年過了多少天 d2 = 天數 * 如果2012年這一年有366天就要讓間隔的天數+1,因為2月份有29日。 * @param maxDays 用於記錄一年中有365天還是366天 * @param d1 表示在這年中過了多少天 * @param d2 表示在這年中過了多少天 * @param y1 當前為2012年 * @param y2 當前為2012年 * @param calendar 根據日曆對象來擷取一年中有多少天 * @return 計算後日期間隔的天數 */ public static int numerical(int maxDays, int d1, int d2, int y1, int y2, Calendar calendar){ int day = d1 - d2; int betweenYears = y1 - y2; List<Integer> d366 = new ArrayList<Integer>(); if(calendar.getActualMaximum(Calendar.DAY_OF_YEAR) == 366){ System.out.println(calendar.getActualMaximum(Calendar.DAY_OF_YEAR)); day += 1; } for (int i = 0; i < betweenYears; i++) { // 當年 + 1 設定下一年中有多少天 calendar.set(Calendar.YEAR, (calendar.get(Calendar.YEAR)) + 1); maxDays = calendar.getActualMaximum(Calendar.DAY_OF_YEAR); // 第一個 366 天不用 + 1 將所有366記錄,先不進行加入然後再少加一個 if(maxDays != 366){ day += maxDays; }else{ d366.add(maxDays); } // 如果最後一個 maxDays 等於366 day - 1 if(i == betweenYears-1 && betweenYears > 1 && maxDays == 366){ day -= 1; } } for(int i = 0; i < d366.size(); i++){ // 一個或一個以上的366天 if(d366.size() >= 1){ day += d366.get(i); } } return day; } /** * 將日期文字裝換成日期 * @param strDate 日期支援年月日 樣本:yyyyMMdd * @return 1970年1月1日器日期的毫秒數 */ public static long getDateTime(String strDate) { return getDateByFormat(strDate, "yyyyMMdd").getTime(); } /** * @param strDate 日期文字 * @param format 日期格式 * @return Date */ public static Date getDateByFormat(String strDate, String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); try{ return (sdf.parse(strDate)); }catch (Exception e){ return null; } } |
例2
| 代碼如下 |
複製代碼 |
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class test16 {
/** * @param args * @throws ParseException */ public static void main(String[] args) throws ParseException { // TODO Auto-generated method stub SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date d1=sdf.parse("2012-09-08 10:10:10"); Date d2=sdf.parse("2012-09-15 00:00:00"); System.out.println(daysBetween(d1,d2)); System.out.println(daysBetween("2012-09-08 10:10:10","2012-09-15 00:00:00")); } /** * 計算兩個日期之間相差的天數 * @param smdate 較小的時間 * @param bdate 較大的時間 * @return 相差天數 * @throws ParseException */ public static int daysBetween(Date smdate,Date bdate) throws ParseException { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); smdate=sdf.parse(sdf.format(smdate)); bdate=sdf.parse(sdf.format(bdate)); 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 Integer.parseInt(String.valueOf(between_days)); } /** *字串的日期格式的計算 */ public static int daysBetween(String smdate,String bdate) throws ParseException{ SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); Calendar cal = Calendar.getInstance(); cal.setTime(sdf.parse(smdate)); long time1 = cal.getTimeInMillis(); cal.setTime(sdf.parse(bdate)); long time2 = cal.getTimeInMillis(); long between_days=(time2-time1)/(1000*3600*24); return Integer.parseInt(String.valueOf(between_days)); } } |
例3
| 代碼如下 |
複製代碼 |
//取得剩餘天數 SimpleDateFormat df=new SimpleDateFormat("yyyymmdd"); Date d0=new java.util.Date(); Date d1=df.parse(end_date); long time0=d0.getTime(); long time1=d1.getTime(); System.out.println((time1-time0)/(1000*60*60*24)); |
這樣算兩個時間相差的天數比較好
| 代碼如下 |
複製代碼 |
/** * 計算兩個日期之間相差的天數 * * @param date1 * @param date2 * @return */ public static int diffdates(Date date1, Date date2) { int result = 0; ElapsedTime et = new ElapsedTime(); GregorianCalendar gc1 = new GregorianCalendar(); GregorianCalendar gc2 = new GregorianCalendar(); gc1.setTime(date1); gc2.setTime(date2); result = et.getDays(gc1, gc2); return result; } |
然後ElapseTime中的方法是:
| 代碼如下 |
複製代碼 |
public int getDays(GregorianCalendar g1, GregorianCalendar g2) { int elapsed = 0; GregorianCalendar gc1, gc2; if (g2.after(g1)) { gc2 = (GregorianCalendar) g2.clone(); gc1 = (GregorianCalendar) g1.clone(); } else { gc2 = (GregorianCalendar) g1.clone(); gc1 = (GregorianCalendar) g2.clone(); } gc1.clear(Calendar.MILLISECOND); gc1.clear(Calendar.SECOND); gc1.clear(Calendar.MINUTE); gc1.clear(Calendar.HOUR_OF_DAY); gc2.clear(Calendar.MILLISECOND); gc2.clear(Calendar.SECOND); gc2.clear(Calendar.MINUTE); gc2.clear(Calendar.HOUR_OF_DAY); while (gc1.before(gc2)) { gc1.add(Calendar.DATE, 1); elapsed++; } return elapsed; } |
其實使用joda最簡單
| 代碼如下 |
複製代碼 |
public boolean isRentalOverdue(DateTime datetimeRented) { Period rentalPeriod = Period.days(2); return datetimeRented.plus(rentalPeriod).isBeforeNow() } |