DayUtils 处理开始时间和结束时间的工具类

 
import java.util.Calendar;
import java.util.Date;


import org.nutz.lang.Times;
public class DayUtils {

	public static String timeFormat(Date tim){
		return Times.format("yyyyMMdd", tim);
	}

	public static String standardTimeFormat(Date tim){
		return standardTimeFormat(tim, "yyyy-MM-dd");
	}
	
	public static String standardTiFormat(Date tim){
		return standardTimeFormat(tim, "yyyy_MM_dd");
	}
	
	public static String standardTimeFormat(Date tim,String pattern){
		return Times.format(pattern, tim);
	}

	public static int getRangeDays(long beginTime, long endTime){
		int rangeDays = 0;
		Calendar ca1 = Calendar.getInstance();
		ca1.setTimeInMillis(beginTime);

		Calendar ca2 = Calendar.getInstance();
		ca2.setTimeInMillis(endTime);

		int year1 = ca1.get(Calendar.YEAR);
		int year2 = ca2.get(Calendar.YEAR);
		// 判断是否是同一年
		if (year1 == year2) {
			rangeDays = ca2.get(Calendar.DAY_OF_YEAR)
					- ca1.get(Calendar.DAY_OF_YEAR);
		} else if (year2 > year1) {
			int max = ca1.getActualMaximum(Calendar.DAY_OF_YEAR);
			int firstDay = max - ca1.get(Calendar.DAY_OF_YEAR);
			rangeDays = firstDay + ca2.get(Calendar.DAY_OF_YEAR);
			// 假如超过一年,则加上中间这些年的天数
			if (year2 - year1 > 1) {
				for (int i = year1 + 1; i < year2; i++) {
					Calendar ca = Calendar.getInstance();
					ca.set(Calendar.YEAR, i);
					int maxday = ca.getActualMaximum(Calendar.DAY_OF_YEAR);
					rangeDays += maxday;
				}
			}
		}

		return rangeDays;
	}

}

你可能感兴趣的:(工具类)