本文實例講述了Android編程實現計算兩個日期之間天數并打印所有日期的方法。分享給大家供大家參考,具體如下:
以下代碼是計算兩個日期之間的天數,并打印所有日期
注:開始時,增加天數時,一天的毫秒數直接用24*60*60*1000來逐步增加天數,再測試時發現,當兩個日期之間的天數超過24天時,打印的日期反而在開始日期之前了,(如打印2016/12/18-2017/1/23,打印的日期反而有2016/12/1),后來發現原因在于24*60*60*1000是一個int值,int值的取值范圍在2的31次方:+/- 2147483648,當超過最大數時,就會變成最小數,這樣反而導致日期變小,將24*60*60*1000變為long類型的值即可:private long static final long ONE_DAY_MS=24*60*60*1000
/*** 計算兩個日期之間的日期* @param startTime* @param endTime*/private void betweenDays(long startTime,long endTime,long mills_select,int code){ Date date_start=new Date(startTime); Date date_end=new Date(endTime); //計算日期從開始時間于結束時間的0時計算 Calendar fromCalendar = Calendar.getInstance(); fromCalendar.setTime(date_start); fromCalendar.set(Calendar.HOUR_OF_DAY, 0); fromCalendar.set(Calendar.MINUTE, 0); fromCalendar.set(Calendar.SECOND, 0); fromCalendar.set(Calendar.MILLISECOND, 0); Calendar toCalendar = Calendar.getInstance(); toCalendar.setTime(date_end); toCalendar.set(Calendar.HOUR_OF_DAY, 0); toCalendar.set(Calendar.MINUTE, 0); toCalendar.set(Calendar.SECOND, 0); toCalendar.set(Calendar.MILLISECOND, 0); int s = (int) ((toCalendar.getTimeInMillis() - fromCalendar.getTimeInMillis())/ (ONE_DAY_MS)); if(s>0){ for(int i = 0;i<=s;i++){ long todayDate = fromCalendar.getTimeInMillis() + i * ONE_DAY_MS; /** * yyyy-MM-dd E :2012-09-01 */ Log.i("打印日期",Utils.getCustonFormatTime(todayDate,"yyyy-MM-dd")); } }else {//此時在同一天之內 Log.i("打印日期",Utils.getCustonFormatTime(startTime,"yyyy-MM-dd")); }}Utils.getCustonFormatTime()方法代碼如下:
/*** 格式化傳入的時間** @param time 需要格式化的時間* @param formatStr 格式化的格式* @return*/public static String getCustonFormatTime(long time, String formatStr) { SimpleDateFormat format = new SimpleDateFormat(formatStr); Date d1 = new Date(time); return format.format(d1);}PS:這里再為大家推薦幾款關于日期與時間計算的在線工具供大家參考使用:
在線日期/天數計算器:
http://tools.VeVB.COm/jisuanqi/date_jisuanqi
在線萬年歷日歷:
http://tools.VeVB.COm/bianmin/wannianli
在線陰歷/陽歷轉換工具:
http://tools.VeVB.COm/bianmin/yinli2yangli
Unix時間戳(timestamp)轉換工具:
http://tools.VeVB.COm/code/unixtime
更多關于Android相關內容感興趣的讀者可查看本站專題:《Android日期與時間操作技巧總結》、《Android開發入門與進階教程》、《Android基本組件用法總結》、《Android視圖View技巧總結》、《Android布局layout技巧總結》及《Android控件用法總結》
希望本文所述對大家Android程序設計有所幫助。
新聞熱點
疑難解答