1. import java.text.DateFormat; 2. import java.text.ParseException; 3. import java.util.Date; 4. 5. /** 6. * @description 計算两个日期相差的天数 7. * @author ZhouJingxian 8. * 9. */ 10. public class CountDate { 11. 12. /** 13. * @param args 14. */ 15. public static void main(String[] args) { 16. Date earlydate = new Date(); 17. Date latedate = new Date(); 18. DateFormat df = DateFormat.getDateInstance(); 19. try { 20. earlydate = df.parse("2009-07-01" ); 21. latedate = df.parse("2009-08-05" ); 22. } catch (ParseException e) { 23. e.printStackTrace(); 24. } 25. 26. int days = daysBetween(earlydate,latedate); 27. 28. System.out.println(days); 29. } 30. 31. /** 32. * 計算两个日期相差的天数 33. * @param early 開始日期 34. * @param late 結束日期 35. * @return 36. */ 37. public static final int daysBetween(Date early, Date late) { 38. java.util.Calendar calst = java.util.Calendar.getInstance(); 39. java.util.Calendar caled = java.util.Calendar.getInstance(); 40. calst.setTime(early); 41. caled.setTime(late); 42. //设置时间为0 时 43. calst.set(java.util.Calendar.HOUR_OF_DAY, 0 ); 44. calst.set(java.util.Calendar.MINUTE, 0 ); 45. calst.set(java.util.Calendar.SECOND, 0 ); 46. caled.set(java.util.Calendar.HOUR_OF_DAY, 0 ); 47. caled.set(java.util.Calendar.MINUTE, 0 ); 48. caled.set(java.util.Calendar.SECOND, 0 ); 49. 50. //得到两个日期相差的天数 51. int days = ((int) (caled.getTime().getTime() / 1000 ) - (int) (calst 52. .getTime().getTime() / 1000 )) / 3600 / 24 ; 53. 54. return days; 55. } 56. 57. 58. }