Java中計算兩個日期相差幾天

          public class Test {
          public void dateDiff(String startTime, String endTime, String format) {
          //按照傳入的格式生成一個simpledateformate對象
          SimpleDateFormat sd = new SimpleDateFormat(format);
          long nd = 1000*24*60*60;//一天的毫秒數(shù)
          long nh = 1000*60*60;//一小時的毫秒數(shù)
          long nm = 1000*60;//一分鐘的毫秒數(shù)
          long ns = 1000;//一秒鐘的毫秒數(shù)
          long diff;
          try {
          //獲得兩個時間的毫秒時間差異
          diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
          long day = diff/nd;//計算差多少天
          long hour = diff%nd/nh;//計算差多少小時
          long min = diff%nd%nh/nm;//計算差多少分鐘
          long sec = diff%nd%nh%nm/ns;//計算差多少秒
          //輸出結果
          System.out.println("時間相差:"+day+"天"+hour+"小時"+min+"分鐘"+sec+"秒。");
          } catch (ParseException e) {
          e.printStackTrace();
          }
          }

          public static void main(String[] args) {
          new Test().dateDiff(new SimpleDateFormat("yyyy-MM-dd").format(new Date()), "2011-4-28", "yyyy-MM-dd");
          }
          }



          posted on 2012-02-14 21:31 脈凌網(wǎng)絡 閱讀(2062) 評論(1)  編輯  收藏

          評論

          # re: Java中計算兩個日期相差幾天 2012-02-15 11:35 旭日  回復  更多評論   

          不錯

          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導航:
           
          主站蜘蛛池模板: 福贡县| 荆州市| 社旗县| 汉阴县| 宣汉县| 明光市| 宜宾市| 宁夏| 大港区| 昂仁县| 左贡县| 共和县| 巨鹿县| 洞头县| 永安市| 杭锦后旗| 隆昌县| 隆安县| 沂水县| 罗山县| 靖安县| 辛集市| 荔浦县| 锡林郭勒盟| 格尔木市| 郁南县| 永安市| 贵港市| 库伦旗| 小金县| 胶州市| 岳池县| 恭城| 肥西县| 托里县| 扎兰屯市| 平原县| 兴山县| 海阳市| 漳浦县| 绥芬河市|