废话不多说直接上代码
获取几天前,几天后,当天的时间
/** * description: 获取时间字符串 * * @param days 负数为过去,正数为未来 * @return java.lang.String * @author bo * @date 2023/2/21 10:26 AM */ public static String accessTimeString(Integer days) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar calendar = new GregorianCalendar(); calendar.setTime(new Date()); calendar.add(Calendar.DATE, days); return sdf.format(calendar.getTime()); }
获取上周日的时间
/** * description: 获取上周日的时间 * * @return java.lang.String * @author bo * @date 2023/3/28 17:49 */ public static String getLastSunDayTime() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar calendarEnd = Calendar.getInstance(); calendarEnd.setTime(new Date()); // 判断当前日期是否为周末,因为周末是本周第一天,如果不向后推迟一天的到的将是下周一的零点,而不是本周周一零点 if (1 == calendarEnd.get(Calendar.DAY_OF_WEEK)) { calendarEnd.add(Calendar.DATE, -1); } calendarEnd.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); return sdf.format(calendarEnd.getTime()); }
将时间格式格式为*“yyyy-MM-DDTHH:mm:ss+TIMEZONE”*转换为指定格式的时间字符串
/** * 将时间格式格式为"yyyy-MM-DDTHH:mm:ss+TIMEZONE"转换为指定格式的时间字符串 * * @param inputTime 待转换的时间字符串, * @param outputFormat 输出时间的格式,如"yyyy-MM-dd HH:mm:ss" * @return 转换后的时间字符串 */ public static String convertTimeFormat(String inputTime, String outputFormat) throws ParseException { // 创建输入格式化器 SimpleDateFormat inputFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss+08:00"); // 创建输出格式化器 SimpleDateFormat outputFormatter = new SimpleDateFormat(outputFormat); // 将输入的时间字符串解析为Date对象 Date date = inputFormatter.parse(inputTime); // 获取系统默认时区 TimeZone timeZone = TimeZone.getDefault(); // 设置输出格式化器的时区 outputFormatter.setTimeZone(timeZone); // 将Date对象转换为指定格式的时间字符串 return outputFormatter.format(date); }
获取今天是周几
/** * 获取今天是周几 * * @return int */ public static int getNowWeekNum() { Calendar calendar = Calendar.getInstance(); return (calendar.get(Calendar.DAY_OF_WEEK) - 1) == 0 ? 7 : (calendar.get(Calendar.DAY_OF_WEEK) - 1); }
判断传入日期是否是今天
public static boolean getIsToday(Date date) { DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"); LocalDateTime localTime = LocalDateTime.parse(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date), dtf); LocalDateTime startTime = LocalDate.now().atTime(0, 0, 0); LocalDateTime endTime = LocalDate.now().atTime(23, 59, 59); return localTime.isAfter(startTime) && localTime.isBefore(endTime); }