Java獲取月初月末以及比較時間在某個區間
阿新 • • 發佈:2018-12-20
一.案例
package org.hyena.dorm.publics.util; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * @author 作者 hq.zheng: * @version 建立時間:2018-11-8 上午8:22:59 * 時間工具類 */ public class DormDateTimeUtil { /** * 判斷當前時間是否在[startTime, endTime]區間,注意時間格式要一致 * * @param nowTime 當前時間 * @param startTime 開始時間 * @param endTime 結束時間 * @return * @author hq.zheng */ public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) { if (nowTime.getTime() == startTime.getTime() || nowTime.getTime() == endTime.getTime()) { return true; } Calendar date = Calendar.getInstance(); date.setTime(nowTime); Calendar begin = Calendar.getInstance(); begin.setTime(startTime); Calendar end = Calendar.getInstance(); end.setTime(endTime); if (date.after(begin) && date.before(end)) { return true; } else { return false; } } /** * 獲取當前月的第一天 * * @return * @author hq.zheng */ public static Date getThisMonthFirstDay(){ Calendar cale = Calendar.getInstance(); cale.add(Calendar.MONTH, 0); cale.set(Calendar.DAY_OF_MONTH, 1); return cale.getTime(); } /** * 獲取當前月的最後一天 * * @return * @author hq.zheng */ public static Date getThisMonthLastday(){ Calendar cale = Calendar.getInstance(); cale.add(Calendar.MONTH, 1); cale.set(Calendar.DAY_OF_MONTH, 0); return cale.getTime(); } /** * 獲取上月的第一天 * * @return * @author hq.zheng */ public static Date getPrecedMonthFirstDay(){ Calendar cale = Calendar.getInstance(); cale = Calendar.getInstance(); cale.add(Calendar.MONTH, -1); cale.set(Calendar.DAY_OF_MONTH, 1); return cale.getTime(); } /** * 獲取上月的最後一天 * * @return * @author hq.zheng */ public static Date getPrecedMonthLastday(){ Calendar cale = Calendar.getInstance(); cale = Calendar.getInstance(); cale.add(Calendar.MONTH, 0); cale.set(Calendar.DAY_OF_MONTH, 0); return cale.getTime(); } /** * 將字串時間轉成日期時間 * * @param nowDate 當前時間 * @param format 轉的格式,如[yyyy-MM-dd],[yyyy年MM月dd日 HH時mm分ss秒] * @return * @author hq.zheng */ public static Date formatStringToDate(String nowDate,String format){ SimpleDateFormat sdf = new SimpleDateFormat(format); Date date=null; try { date=sdf.parse(nowDate); } catch (Exception e) { e.printStackTrace(); return date; } return date; } }