• java计算两个日期相差多少天


    java计算两个日期相差多少天

    public class DateUtil{
    	public static int betweenDays(Date startDate, Date endDate ) throws Exception {
    		Calendar beginCalendar = Calendar.getInstance();
    		Calendar endCalendar = Calendar.getInstance() ; 
    		
    		try {
    			beginCalendar.setTime( startDate ) ;
    			endCalendar.setTime( endDate ) ;
    			
    			if (beginCalendar.get(Calendar.YEAR) == endCalendar.get(Calendar.YEAR)) {
    				return endCalendar.get(Calendar.DAY_OF_YEAR)
    						- beginCalendar.get(Calendar.DAY_OF_YEAR);
    			} else {
    				if (beginCalendar.getTimeInMillis() < endCalendar.getTimeInMillis()) {
    					int days = beginCalendar.getActualMaximum(Calendar.DAY_OF_YEAR)
    							- beginCalendar.get(Calendar.DAY_OF_YEAR)
    							+ endCalendar.get(Calendar.DAY_OF_YEAR);
    					for (int i = beginCalendar.get(Calendar.YEAR) + 1; i < endCalendar
    							.get(Calendar.YEAR); i++) {
    						Calendar c = Calendar.getInstance();
    						c.set(Calendar.YEAR, i);
    						days += c.getActualMaximum(Calendar.DAY_OF_YEAR);
    					}
    					return days;
    				} else {
    					int days =endCalendar.getActualMaximum(Calendar.DAY_OF_YEAR)
    							- endCalendar.get(Calendar.DAY_OF_YEAR)
    							+ beginCalendar.get(Calendar.DAY_OF_YEAR);
    					for (int i = endCalendar.get(Calendar.YEAR) + 1; i < beginCalendar
    							.get(Calendar.YEAR); i++) {
    						Calendar c = Calendar.getInstance();
    						c.set(Calendar.YEAR, i);
    						days += c.getActualMaximum(Calendar.DAY_OF_YEAR);
    					}
    					return days;
    				}
    			}
    		} catch (Exception e) {
    			throw e;
    		}
    	}
    	
    }


  • 相关阅读:
    200. Number of Islands
    [Leetcode] 70. Climbing Stairs Java
    LeetCode 64. Minimum Path Sum Java
    LeetCode 63. Unique Paths II Java
    LeetCode 62. Unique Paths Java
    [LeetCode 241] Different Ways to Add Parentheses Java
    LeetCode 240. Search a 2D Matrix II Java
    LeetCode 215. Kth Largest Element in an Array Java
    LeetCode 169. Majority Element Java
    LeetCode 53. Maximum Subarray Java
  • 原文地址:https://www.cnblogs.com/james1207/p/3297098.html
Copyright © 2020-2023  润新知