Java斷定兩個日期相差天數的辦法。本站提示廣大學習愛好者:(Java斷定兩個日期相差天數的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是Java斷定兩個日期相差天數的辦法正文
本文實例講述了Java斷定兩個日期相差天數的辦法。分享給年夜家供年夜家參考。詳細以下:
import java.util.Calendar; public class DateDifferent{ public static void main(String[] args){ Calendar calendar1 = Calendar.getInstance(); Calendar calendar2 = Calendar.getInstance(); calendar1.set(2007, 01, 10); calendar2.set(2007, 07, 01); long milliseconds1 = calendar1.getTimeInMillis(); long milliseconds2 = calendar2.getTimeInMillis(); long diff = milliseconds2 - milliseconds1; long diffSeconds = diff / 1000; long diffMinutes = diff / (60 * 1000); long diffHours = diff / (60 * 60 * 1000); long diffDays = diff / (24 * 60 * 60 * 1000); System.out.println("\nThe Date Different Example"); System.out.println("Time in milliseconds: " + diff + " milliseconds."); System.out.println("Time in seconds: " + diffSeconds + " seconds."); System.out.println("Time in minutes: " + diffMinutes + " minutes."); System.out.println("Time in hours: " + diffHours + " hours."); System.out.println("Time in days: " + diffDays + " days."); } }
把下面的代碼放在項目裡應用了一下,【求日期部門】是要滿24小時才算一天的,不太順應項目標需求,故改成如許子。
/** * 獲得兩個日期相差的天數 */ public static int getBetweenDay(Date date1, Date date2) { Calendar d1 = new GregorianCalendar(); d1.setTime(date1); Calendar d2 = new GregorianCalendar(); d2.setTime(date2); int days = d2.get(Calendar.DAY_OF_YEAR)- d1.get(Calendar.DAY_OF_YEAR); System.out.println("days="+days); int y2 = d2.get(Calendar.YEAR); if (d1.get(Calendar.YEAR) != y2) { // d1 = (Calendar) d1.clone(); do { days += d1.getActualMaximum(Calendar.DAY_OF_YEAR); d1.add(Calendar.YEAR, 1); } while (d1.get(Calendar.YEAR) != y2); } return days; }
願望本文所述對年夜家的java法式設計有所贊助。