123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344 |
- package com.ruoyi.common.utils;
- import java.lang.management.ManagementFactory;
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.time.*;
- import java.time.format.DateTimeFormatter;
- import java.time.format.DateTimeParseException;
- import java.time.temporal.TemporalAdjusters;
- import java.util.ArrayList;
- import java.util.Calendar;
- import java.util.Date;
- import java.util.List;
- import org.apache.commons.lang3.time.DateFormatUtils;
- /**
- * 时间工具类
- *
- * @author ruoyi
- */
- public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
- public static String YYYY = "yyyy";
- public static String YYYY_MM = "yyyy-MM";
- public static String YYYY_MM_DD = "yyyy-MM-dd";
- public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
- public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
- public static String YYYYMMDD = "yyyyMMdd";
- private static String[] parsePatterns = {
- "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
- "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
- "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
- public static String getDateNow() {
- return dateTimeNow(YYYYMMDD);
- }
- /**
- * 获取当前Date型日期
- *
- * @return Date() 当前日期
- */
- public static Date getNowDate() {
- return new Date();
- }
- /**
- * 获取当前日期, 默认格式为yyyy-MM-dd
- *
- * @return String
- */
- public static String getDate() {
- return dateTimeNow(YYYY_MM_DD);
- }
- public static String getYear() {
- return dateTimeNow(YYYY);
- }
- public static final String getTime() {
- return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
- }
- public static final String dateTimeNow() {
- return dateTimeNow(YYYYMMDDHHMMSS);
- }
- public static final String dateTimeNow(final String format) {
- return parseDateToStr(format, new Date());
- }
- public static final String dateTime(final Date date) {
- return parseDateToStr(YYYY_MM_DD, date);
- }
- public static final String parseDateToStr(final String format, final Date date) {
- return new SimpleDateFormat(format).format(date);
- }
- public static final Date dateTime(final String format, final String ts) {
- try {
- return new SimpleDateFormat(format).parse(ts);
- } catch (ParseException e) {
- throw new RuntimeException(e);
- }
- }
- /**
- * 日期路径 即年/月/日 如2018/08/08
- */
- public static final String datePath() {
- Date now = new Date();
- return DateFormatUtils.format(now, "yyyy/MM/dd");
- }
- /**
- * 日期路径 即年/月/日 如20180808
- */
- public static final String dateTime() {
- Date now = new Date();
- return DateFormatUtils.format(now, "yyyyMMdd");
- }
- /**
- * 日期型字符串转化为日期 格式
- */
- public static Date parseDate(Object str) {
- if (str == null) {
- return null;
- }
- try {
- return parseDate(str.toString(), parsePatterns);
- } catch (ParseException e) {
- return null;
- }
- }
- /**
- * 将字符串转换为Date对象(支持多种格式)
- * @param dateString 日期字符串
- * @return 对应的Date对象,解析失败返回null
- */
- public static Date convertStringToDate(String dateString) {
- // 定义可能的日期格式(按优先级排序)
- for (String pattern : parsePatterns) {
- try {
- DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
- LocalDate localDate = LocalDate.parse(dateString, formatter);
- return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
- } catch (DateTimeParseException e) {
- // 尝试下一个格式
- }
- }
- return null; // 所有格式都尝试失败
- }
- /**
- * 获取服务器启动时间
- */
- public static Date getServerStartDate() {
- long time = ManagementFactory.getRuntimeMXBean().getStartTime();
- return new Date(time);
- }
- /**
- * 计算相差天数
- */
- public static int differentDaysByMillisecond(Date date1, Date date2) {
- return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
- }
- /**
- * 计算两个时间差
- */
- public static String getDatePoor(Date endDate, Date nowDate) {
- long nd = 1000 * 24 * 60 * 60;
- long nh = 1000 * 60 * 60;
- long nm = 1000 * 60;
- // long ns = 1000;
- // 获得两个时间的毫秒时间差异
- long diff = endDate.getTime() - nowDate.getTime();
- // 计算差多少天
- long day = diff / nd;
- // 计算差多少小时
- long hour = diff % nd / nh;
- // 计算差多少分钟
- long min = diff % nd % nh / nm;
- // 计算差多少秒//输出结果
- // long sec = diff % nd % nh % nm / ns;
- return day + "天" + hour + "小时" + min + "分钟";
- }
- /**
- * 增加 LocalDateTime ==> Date
- */
- public static Date toDate(LocalDateTime temporalAccessor) {
- ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
- return Date.from(zdt.toInstant());
- }
- /**
- * 增加 LocalDate ==> Date
- */
- public static Date toDate(LocalDate temporalAccessor) {
- LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
- ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
- return Date.from(zdt.toInstant());
- }
- /**
- * 根据时间加减时间(时间可为负)
- *
- * @param dateTime 时间
- * @param seconds 加减的天数
- * @param format 日期格式(与dateTime格式一致)
- * @return
- */
- public static String plusSeconds(String dateTime, int seconds, String format) {
- //LocalDateTime parse = parse(dateTime, format);
- //LocalDateTime localDateTime = parse.plusMinutes(seconds);
- LocalDate parse = LocalDate.parse(dateTime);
- LocalDate localDate = LocalDate.now().plusDays(seconds);
- String date = localDate.format(DateTimeFormatter.ofPattern(format));
- return date;
- }
- /***
- * 判断某一个日期是星期几
- * @param datetime
- * @return
- */
- public static String dateToWeek(String datetime) {
- SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
- String[] weekDays = {"0", "1", "2", "3",
- "4", "5", "6"};
- Calendar cal = Calendar.getInstance(); // 获得一个日历
- Date datet = null;
- try {
- datet = f.parse(datetime);
- cal.setTime(datet);
- } catch (ParseException e) {
- e.printStackTrace();
- }
- int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
- if (w < 0)
- w = 0;
- return weekDays[w];
- }
- /***
- * 获取传入日期的前一天日期
- * @param dateTime
- * @return
- */
- public static String getYesterday(String dateTime) {
- SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD);
- Date date = null;
- try {
- date = sdf.parse(dateTime);
- } catch (ParseException e) {
- throw new RuntimeException(e);
- }
- // 往前一天
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(date);
- calendar.add(Calendar.DATE, -1);
- Date dateMinusOneDay = calendar.getTime();
- String dateMinusOneDayStr = sdf.format(dateMinusOneDay);
- System.out.println("往前一天的日期: " + dateMinusOneDayStr);
- return dateMinusOneDayStr;
- }
- /**
- * 获取指定月份的最后一天日期(格式为yyyy-MM-dd)
- *
- * @param year 年份(如2023)
- * @param month 月份(1-12)
- * @return 最后一天日期字符串(如"2023-02-28")
- * @throws IllegalArgumentException 如果月份不在1-12范围内
- */
- public static String getLastDayOfMonth(int year, int month) {
- // 验证月份是否有效
- if (month < 1 || month > 12) {
- throw new IllegalArgumentException("月份必须在1-12之间");
- }
- // 使用YearMonth获取月份的最后一天并格式化为字符串
- return YearMonth.of(year, month)
- .atEndOfMonth()
- .format(DateTimeFormatter.ISO_DATE);
- }
- /**
- * 判断目标日期是否在[startDate, endDate]区间内(包含边界)
- *
- * @param target 目标日期 (Date类型)
- * @param start 开始日期 (Date类型)
- * @param end 结束日期 (Date类型)
- * @return 若target在[start, end]区间内返回true,否则返回false
- */
- public static boolean isDateBetween(Date target, Date start, Date end) {
- // 转换为LocalDate(忽略时间部分)
- LocalDate targetDate = convertToLocalDate(target);
- LocalDate startDate = convertToLocalDate(start);
- LocalDate endDate = convertToLocalDate(end);
- // 判断日期区间(包含边界)
- return (targetDate.isEqual(startDate) || targetDate.isAfter(startDate))
- && (targetDate.isEqual(endDate) || targetDate.isBefore(endDate));
- }
- /**
- * 将Date转换为LocalDate(格式化为yyyy-MM-dd)
- */
- private static LocalDate convertToLocalDate(Date date) {
- return date.toInstant()
- .atZone(ZoneId.systemDefault())
- .toLocalDate();
- }
- /**
- * 获取当期月份,只要月份,不要年
- */
- public static String justMonth() {
- // 获取当前月份数字
- int monthNumber = LocalDate.now().getMonthValue();
- // 获取带前导零的月份字符串
- String monthPadded = String.format("%02d", monthNumber);
- return monthPadded;
- }
- /**
- * 获取本周周一至周六的日期字符串列表(格式:yyyy-MM-dd)
- * @return 包含6个日期字符串的List
- */
- public static List<String> getWeekDatesFromMondayToSaturday() {
- List<String> dates = new ArrayList<>(6);
- DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
- // 获取本周周一(如果今天是周一则返回今天)
- LocalDate monday = LocalDate.now()
- .with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
- // 添加周一到周六的日期字符串
- for (int i = 0; i < 6; i++) {
- dates.add(monday.plusDays(i).format(formatter));
- }
- return dates;
- }
- }
|