时间处理(今天,昨天,本周,本月)


public
static List<Date> today() throws ParseException { List<Date> listDate = new ArrayList<>(); //今天 Date date = new Date(); //明天 Date date2 = new Date(date.getTime() + 24 * 3600 * 1000); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); String formatDate = dateFormat.format(date); String formatDate2 = dateFormat.format(date2); Date today = dateFormat.parse(formatDate); Date tomorrow = dateFormat.parse(formatDate2); listDate.add(today); listDate.add(tomorrow); return listDate; } /** * 昨天 * * @return * @throws ParseException */ public static List<Date> yestoday() throws ParseException { List<Date> listDate = new ArrayList<>(); //今天 Date date = new Date(); //昨天 Date date2 = new Date(date.getTime() - 24 * 3600 * 1000); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); String formatDate = dateFormat.format(date); String formatDate2 = dateFormat.format(date2); Date today = dateFormat.parse(formatDate); Date yestoday = dateFormat.parse(formatDate2); listDate.add(today); listDate.add(yestoday); return listDate; } /** * 本周 * * @return * @throws ParseException */ public static List<Date> week() throws ParseException { List<Date> listDate = new ArrayList<>(); //获取周一的值 LocalDate today = LocalDate.now(); LocalDate toweekMonday = today.with(DayOfWeek.MONDAY); LocalDate sunDay = today.with(DayOfWeek.SUNDAY); ZoneId zoneId = ZoneId.systemDefault(); ZonedDateTime zonedDateTime = toweekMonday.atStartOfDay(zoneId); Date monday = Date.from(zonedDateTime.toInstant()); ZonedDateTime zonedDateTime2 = sunDay.atStartOfDay(zoneId); Date sunday = Date.from(zonedDateTime2.toInstant()); //转化date类型 listDate.add(monday); listDate.add(sunday); return listDate; } /** * 本月 * @return * @throws ParseException */ public static List<Date> month() throws ParseException { List<Date> listDate = new ArrayList<>(); /** * 本月第一天 */ SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); GregorianCalendar gc2 = (GregorianCalendar) Calendar.getInstance(); Calendar calendar2 = Calendar.getInstance(); gc2.setTime(new Date()); gc2.set(Calendar.DAY_OF_MONTH, 1); //设置该月的第一天 String b_day_first = df.format(gc2.getTime()); StringBuffer str_b = new StringBuffer().append(b_day_first).append(" 00:00:00");//拼接 时分秒 b_day_first = str_b.toString(); /** * 本月最后一天 */ calendar2.add(Calendar.MONTH, 1); //加一个月 calendar2.set(Calendar.DATE, 1); //设置为该月第一天 calendar2.add(Calendar.DATE, -1); //再减一天即为上个月最后一天 String b_day_last = df.format(calendar2.getTime()); StringBuffer endStrb = new StringBuffer().append(b_day_last).append("23:59:59"); //拼接 时,分,秒 b_day_last = endStrb.toString(); Date monthFirst = df.parse(b_day_first); Date monthLast = df.parse(b_day_last); listDate.add(monthFirst); listDate.add(monthLast); return listDate; }

猜你喜欢

转载自www.cnblogs.com/hxzDzvBlog/p/9212421.html