java中对获取指定日期开始和结束时间

时间:2025-04-02 15:08:17
package com.qbb.test; import java.util.Calendar; import java.util.Date; public class DateUtil { /** * 获取指定天的开始时间 * @return */ public static Date getStartTimeOfCurrentDay(Date date){ Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setTime(date); setMinTimeOfDay(calendar); return calendar.getTime(); } /** * 获取指定天的结束时间 * @return */ public static Date getEndTimeOfCurrentDay(Date date){ Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setTime(date); setMaxTimeOfDay(calendar); return calendar.getTime(); } /** * 获取指定周的开始时间 * @return */ public static Date getStartTimeOfCurrentWeek(Date date){ Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setTime(date); calendar.setFirstDayOfWeek(Calendar.MONDAY); calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); setMinTimeOfDay(calendar); return calendar.getTime(); } /** * 获取指定周的结束时间 * @return */ public static Date getEndTimeOfCurrentWeek(Date date){ Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setTime(date); calendar.setFirstDayOfWeek(Calendar.MONDAY); calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); setMaxTimeOfDay(calendar); return calendar.getTime(); } /** * 获取指定月的开始时间 * @return */ public static Date getStartTimeOfCurrentMonth(Date date){ Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setTime(date); calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),1); setMinTimeOfDay(calendar); return calendar.getTime(); } /** * 获取指定月的结束时间 * @return */ public static Date getEndTimeOfCurrentMonth(Date date){ Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setTime(date); int maxMonthDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),maxMonthDay); setMaxTimeOfDay(calendar); return calendar.getTime(); } /** * 获取指定年的开始时间 注意月份要减1 * @return */ public static Date getStartTimeOfCurrentYear(Date date){ Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setTime(date); calendar.set(calendar.get(Calendar.YEAR),0,1); setMinTimeOfDay(calendar); return calendar.getTime(); } /** * 获取指定年的结束时间 注意月份要减1 * @return */ public static Date getEndTimeOfCurrentYear(Date date){ Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setTime(date); calendar.set(calendar.get(Calendar.YEAR),11,31); setMaxTimeOfDay(calendar); return calendar.getTime(); } /** * 设置当天的开始时间 * @param calendar */ private static void setMinTimeOfDay(Calendar calendar) { calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.MILLISECOND, 0); } /** * 设置当天的结束时间 * @param calendar */ private static void setMaxTimeOfDay(Calendar calendar) { calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.SECOND, 59); calendar.set(Calendar.MINUTE, 59); calendar.set(Calendar.MILLISECOND, 999); } }