java日期相关方法备忘

 

public class DateUtil {

	private final static String format = "yyyy-MM-dd";
	
	/**
	 * 日期格式转换为字符串
	 * 
	 * @param date
	 * @return
	 */
	public static String dateToString(Date date){
		if(date != null){
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			return sdf.format(date);
		}else{
			return "-";
		}
	}
	
	/**
	 * 将指定格式的字符串转换为日期
	 * @param str
	 * @return
	 */
	public static Date stringToDate(String str){
		Date date = null ;
		if( str != null && str.matches("\\d{4}-\\d{1,2}-\\d{1,2}")){
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			try {
				date = sdf.parse(str);
			} catch (ParseException e) {
				System.out.println("日期转换失败!");
				e.printStackTrace();
			}
		}
		return date ;
	}
	
	/**
	 * 计算两个日期之间的天数
	 * 
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public static Long countDayBetweenDate(Date startDate, Date endDate){
		Calendar fromCalendar = Calendar.getInstance();
        fromCalendar.setTime(startDate);
        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(endDate);
        toCalendar.set(Calendar.HOUR_OF_DAY, 0);  
        toCalendar.set(Calendar.MINUTE, 0);
        toCalendar.set(Calendar.SECOND, 0);
        toCalendar.set(Calendar.MILLISECOND, 0);
        
        return (toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24);
	}
	
	/**
	 * 计算两个日期之间的月数
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public static int countMonthBetweenDate(Date startDate,Date endDate){
		int months = 0 ;
		Calendar tmpStartCalendar = Calendar.getInstance() ;
		tmpStartCalendar.setTime(startDate);
		while(true){
			tmpStartCalendar.add(Calendar.MONTH, 1);
			Date tmpStartDate = tmpStartCalendar.getTime() ;
			if( compareDates(endDate,tmpStartDate) ){
				months += 1 ;
			} else {
				break ;
			}
		}
		return months; 
	}
	
	/**
	 * 获取给定日期的指定月份的天数
	 * @param date
	 * @return
	 */
	public static int getDaysOfMonth(Date date){
		Calendar c = Calendar.getInstance();
		//设置为该月,例如08年1月,日期随意
		c.setTime(date);
		//获得该月的日期
		int max = c.getActualMaximum(Calendar.DATE);
		return max ;
	}
	
	/**
	 * 比较两个日期的大小
	 * 如果两个日期相等,那么将认为第一个日期大于第二个日期
	 * @param d1
	 * @param d2
	 * @return
	 */
	private static boolean compareDates(Date d1 ,Date d2){
		if( d1.getTime() - d2.getTime() >= 0){
			return true ;
		}
		return false ;
	}
}
 

 

你可能感兴趣的:(java)