常用日期封裝方法

 

目錄

 

 

判斷時間是否在時間段內


 

判斷時間是否在時間段內


/**
 * 判斷時間是否在時間段內
 * 
 * @param nowTime   需要判斷的時間
 * @param beginTime
 * @param endTime
 * @return
 */
public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
   Calendar date = Calendar.getInstance();
   date.setTime(nowTime);

   Calendar begin = Calendar.getInstance();
   begin.setTime(beginTime);

   Calendar end = Calendar.getInstance();
   end.setTime(endTime);

   if (date.after(begin) && date.before(end)) {
      return true;
   } else {
      return false;
   }
}

獲取的日期與傳入日期的差值

	/**
	 * @param date
	 * @param day 想要獲取的日期與傳入日期的差值 比如想要獲取傳入日期前四天的日期 day=-4即可
	 * @return
	 */
	public static Date getSomeDay(Date date, int day){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DATE, day);
		return calendar.getTime();
	}

日期差天數

	public static long getDisDay(Date startDate, Date endDate){
		long[] dis = getDisTime(startDate, endDate);
		long day = dis[0];
		if (dis[1] > 0 || dis[2] > 0 || dis[3] > 0) {
			day += 1;
		}
		return day;
	}

日期差天數、小時、分鐘、秒數組

	public static long[] getDisTime(Date startDate, Date endDate){
		long timesDis = Math.abs(startDate.getTime() - endDate.getTime());
		long day = timesDis / (1000 * 60 * 60 * 24);
		long hour = timesDis / (1000 * 60 * 60) - day * 24;
		long min = timesDis / (1000 * 60) - day * 24 * 60 - hour * 60;
		long sec = timesDis / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60;
		return new long[]{day, hour, min, sec};
	}

獲取當天00時

	public static Date getDate00() {
		Calendar calendar1 = Calendar.getInstance();
		calendar1.set(calendar1.get(Calendar.YEAR), calendar1.get(Calendar.MONTH), calendar1.get(Calendar.DAY_OF_MONTH),
				0, 0, 0);
		Date beginOfDate = calendar1.getTime();
		System.out.println(beginOfDate);
		return beginOfDate;
	}

 

發佈了41 篇原創文章 · 獲贊 10 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章