Java--常用日期操作Date、LocalDateTime工具类

两者直接的区别

LocalDateTime和Date的主要区别在于:

  • LocalDateTime是不可变的,而Date是可变的。 LocalDateTime包含了更多的日期时间信息,如纳秒。
  • LocalDateTime提供了更丰富的方法,用于对日期时间进行计算和操作。
  • LocalDateTime不包含任何时区信息,而Date包含时区信息。

下面两个工具类按需copy

Date

/**
 * 日期操作工具类
 */
public class DateUtils {
    /**
     * 日期转换-  String -> Date
     *
     * @param dateString 字符串时间
     * @return Date类型信息
     * @throws Exception 抛出异常
     */
    public static Date parseString2Date(String dateString) throws Exception {
        if (dateString == null) {
            return null;
        }
        return parseString2Date(dateString, "yyyy-MM-dd");
    }

    /**
     * 日期转换-  String -> Date
     *
     * @param dateString 字符串时间
     * @param pattern    格式模板
     * @return Date类型信息
     * @throws Exception 抛出异常
     */
    public static Date parseString2Date(String dateString, String pattern) throws Exception {
        if (dateString == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        Date date = sdf.parse(dateString);
        return date;
    }

    /**
     * 日期转换 Date -> String
     *
     * @param date Date类型信息
     * @return 字符串时间
     * @throws Exception 抛出异常
     */
    public static String parseDate2String(Date date) throws Exception {
        if (date == null) {
            return null;
        }
        return parseDate2String(date, "yyyy-MM-dd");
    }

    /**
     * 日期转换 Date -> String
     *
     * @param date    Date类型信息
     * @param pattern 格式模板
     * @return 字符串时间
     * @throws Exception 抛出异常
     */
    public static String parseDate2String(Date date, String pattern) throws Exception {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String strDate = sdf.format(date);
        return strDate;
    }

    /**
     * 获取当前日期的本周一是几号
     *
     * @return 本周一的日期
     */
    public static Date getThisWeekMonday() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        // 获得当前日期是一个星期的第几天
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
        if (1 == dayWeek) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
        // 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        // 获得当前日期是一个星期的第几天
        int day = cal.get(Calendar.DAY_OF_WEEK);
        // 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
        return cal.getTime();
    }

    /**
     * 获取当前日期周的最后一天
     *
     * @return 当前日期周的最后一天
     */
    public static Date getSundayOfThisWeek() {
        Calendar c = Calendar.getInstance();
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
        if (dayOfWeek == 0) {
            dayOfWeek = 7;
        }
        c.add(Calendar.DATE, -dayOfWeek + 7);
        return c.getTime();
    }

    /**
     * 根据日期区间获取月份列表
     *
     * @param minDate 开始时间
     * @param maxDate 结束时间
     * @return 月份列表
     * @throws Exception
     */
    public static List<String> getMonthBetween(String minDate, String maxDate, String format) throws Exception {
        ArrayList<String> result = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();

        min.setTime(sdf.parse(minDate));
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

        max.setTime(sdf.parse(maxDate));
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
        SimpleDateFormat sdf2 = new SimpleDateFormat(format);

        Calendar curr = min;
        while (curr.before(max)) {
            result.add(sdf2.format(curr.getTime()));
            curr.add(Calendar.MONTH, 1);
        }

        return result;
    }

    /**
     * 根据日期获取年度中的周索引
     *
     * @param date 日期
     * @return 周索引
     * @throws Exception
     */
    public static Integer getWeekOfYear(String date) throws Exception {
        Date useDate = parseString2Date(date);
        Calendar cal = Calendar.getInstance();
        cal.setTime(useDate);
        return cal.get(Calendar.WEEK_OF_YEAR);
    }

    /**
     * 根据年份获取年中周列表
     *
     * @param year 年分
     * @return 周列表
     * @throws Exception
     */
    public static Map<Integer, String> getWeeksOfYear(String year) throws Exception {
        Date useDate = parseString2Date(year, "yyyy");
        Calendar cal = Calendar.getInstance();
        cal.setTime(useDate);
        //获取年中周数量
        int weeksCount = cal.getWeeksInWeekYear();
        Map<Integer, String> mapWeeks = new HashMap<>(55);
        for (int i = 0; i < weeksCount; i++) {
            cal.get(Calendar.DAY_OF_YEAR);
            mapWeeks.put(i + 1, parseDate2String(getFirstDayOfWeek(cal.get(Calendar.YEAR), i)));
        }
        return mapWeeks;
    }

    /**
     * 获取某年的第几周的开始日期
     *
     * @param year 年分
     * @param week 周索引
     * @return 开始日期
     * @throws Exception
     */
    public static Date getFirstDayOfWeek(int year, int week) throws Exception {
        Calendar c = new GregorianCalendar();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, Calendar.JANUARY);
        c.set(Calendar.DATE, 1);

        Calendar cal = (GregorianCalendar) c.clone();
        cal.add(Calendar.DATE, week * 7);

        return getFirstDayOfWeek(cal.getTime());
    }

    /**
     * 获取某年的第几周的结束日期
     *
     * @param year 年份
     * @param week 周索引
     * @return 结束日期
     * @throws Exception
     */
    public static Date getLastDayOfWeek(int year, int week) throws Exception {
        Calendar c = new GregorianCalendar();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, Calendar.JANUARY);
        c.set(Calendar.DATE, 1);

        Calendar cal = (GregorianCalendar) c.clone();
        cal.add(Calendar.DATE, week * 7);

        return getLastDayOfWeek(cal.getTime());
    }

    /**
     * 获取当前时间所在周的开始日期
     *
     * @param date 当前时间
     * @return 开始时间
     */
    public static Date getFirstDayOfWeek(Date date) {
        Calendar c = new GregorianCalendar();
        c.setFirstDayOfWeek(Calendar.SUNDAY);
        c.setTime(date);
        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
        return c.getTime();
    }

    /**
     * 获取当前时间所在周的结束日期
     *
     * @param date 当前时间
     * @return 结束日期
     */
    public static Date getLastDayOfWeek(Date date) {
        Calendar c = new GregorianCalendar();
        c.setFirstDayOfWeek(Calendar.SUNDAY);
        c.setTime(date);
        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6);
        return c.getTime();
    }
    //获得上周一的日期
    public static Date geLastWeekMonday(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(getThisWeekMonday(date));
        cal.add(Calendar.DATE, -7);
        return cal.getTime();
    }

    //获得本周一的日期
    public static Date getThisWeekMonday(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        // 获得当前日期是一个星期的第几天
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
        if (1 == dayWeek) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
        // 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        // 获得当前日期是一个星期的第几天
        int day = cal.get(Calendar.DAY_OF_WEEK);
        // 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
        return cal.getTime();
    }

    //获得下周一的日期
    public static Date getNextWeekMonday(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(getThisWeekMonday(date));
        cal.add(Calendar.DATE, 7);
        return cal.getTime();
    }

    //获得今天日期
    public static Date getToday(){
        return new Date();
    }

    //获得本月一日的日期
    public static Date getFirstDay4ThisMonth(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH,1);
        return calendar.getTime();
    }

    public static void main(String[] args) {
        try {
            System.out.println("本周一" + parseDate2String(getThisWeekMonday()));
            System.out.println("本月一日" + parseDate2String(getFirstDay4ThisMonth()));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


LocalDateTime

Java 8中引入的新时间操作类LocalDateTime,当然也不算太新了毕竟现在都JDK22了

package com.xmz.util.date;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Locale;

/**
 * @author xmz
 * @date 2024/06/14
 */
public class LocalDateUtils {
    /**
     * 获取当前的日期和时间
     *
     * @return 当前时间
     */
    public static LocalDateTime getNowTime() {
        return LocalDateTime.now();
    }


    /**
     * 获取当前的日期和时间
     *
     * @param template 格式模板
     * @return 根据模板格式化当前时间
     */
    public static String getNowTime(String template) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern(template);
        return LocalDateTime.now().format(df);
    }

    /**
     * 根据时区获取指定时区的时间
     *
     * @param timezone 时区
     *                 "UTC",
     *                 "America/New_York",    // 美国东部时间
     *                 "America/Chicago",     // 美国中部时间
     *                 "America/Denver",      // 美国山地时间
     *                 "America/Los_Angeles", // 美国太平洋时间
     *                 "America/Sao_Paulo",   // 巴西时间
     *                 "Europe/London",       // 英国时间
     *                 "Europe/Paris",        // 中欧时间
     *                 "Europe/Berlin",       // 中欧时间
     *                 "Europe/Moscow",       // 莫斯科时间
     *                 "Asia/Tokyo",          // 日本标准时间
     *                 "Asia/Shanghai",       // 中国标准时间
     *                 "Asia/Hong_Kong",      // 香港时间
     *                 "Asia/Singapore",      // 新加坡时间
     *                 "Asia/Seoul",          // 韩国标准时间
     *                 "Australia/Sydney",    // 澳大利亚东部时间
     *                 "Australia/Melbourne", // 澳大利亚东部时间
     *                 "Australia/Perth",     // 澳大利亚西部时间
     *                 "Africa/Cairo",        // 埃及时间
     *                 "Africa/Johannesburg", // 南非标准时间
     *                 "Africa/Lagos",        // 西非时间
     *                 "Indian/Maldives",     // 马尔代夫时间
     *                 "Indian/Mauritius",    // 毛里求斯时间
     *                 "Pacific/Auckland",    // 新西兰标准时间
     *                 "Pacific/Honolulu"     // 夏威夷-阿留申标准时间
     * @return 指定时区的当前时间
     */
    public static LocalDateTime getNowTimezone(String timezone) {
        return ZonedDateTime.now(ZoneId.of(timezone)).toLocalDateTime();
    }

    /**
     * 根据时区获取指定时区的时间
     *
     * @param timezone 时区
     * @param template 格式模板
     * @return 根据模板格式化指定时区的当前时间
     */
    public static String getNowTimezone(String timezone, String template) {
        LocalDateTime dateTime = ZonedDateTime.now(ZoneId.of(timezone)).toLocalDateTime();
        DateTimeFormatter df = DateTimeFormatter.ofPattern(template);
        return dateTime.format(df);
    }

    /**
     * 根据当前时间获取时间戳 秒级
     *
     * @param timezone 时区
     * @return
     */
    public static Long getNowTimestampSeconds() {
        // 获取当前的 LocalDateTime 对象
        LocalDateTime localDateTime = LocalDateTime.now();
        // 转换为 Instant,并获取 Epoch 秒数
        return localDateTime.atZone(ZoneId.systemDefault()).toEpochSecond();
    }

    public static Long getNowTimestampSeconds(String timezone) {
        // 获取当前的 LocalDateTime 对象
        LocalDateTime localDateTime = LocalDateTime.now();
        // 指定时区
        ZoneId zoneId = ZoneId.of(timezone);
        // 转换为 ZonedDateTime,并获取 Epoch 秒数
        return localDateTime.atZone(zoneId).toEpochSecond();
    }

    /**
     * 根据当前时间获取时间戳 毫秒
     *
     * @param timezone 时区
     * @return
     */
    public static Long getNowTimestampMillis() {
        // 获取当前的 LocalDateTime 对象
        LocalDateTime localDateTime = LocalDateTime.now();
        // 转换为 Instant,并获取 Epoch 毫秒数
        return localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

    public static Long getNowTimestampMillis(String timezone) {
        // 获取当前的 LocalDateTime 对象
        LocalDateTime localDateTime = LocalDateTime.now();
        // 指定时区
        ZoneId zoneId = ZoneId.of(timezone);
        // 转换为 ZonedDateTime,并获取 Epoch 毫秒数
        return localDateTime.atZone(zoneId).toInstant().toEpochMilli();
    }

    /**
     * 日期转换-  LocalDateTime -> String
     *
     * @param localDateTime 时间
     * @param template      格式模板
     * @return
     */
    public static String parseLocalDateConvertString(LocalDateTime localDateTime, String template) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern(template);
        return localDateTime.format(df);
    }

    /**
     * 日期转换-  String  -> LocalDateTime
     *
     * @param localDateTime 时间
     * @param template      格式模板
     * @return
     */
    public static LocalDateTime parseStringConvertLocalDate(String localDateTime, String template) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern(template);
        return LocalDateTime.parse(localDateTime, df);
    }


    /**
     * 按天加
     *
     * @param dateTime 时间
     * @param days     天数
     * @return LocalDateTime
     */
    public static LocalDateTime addDays(LocalDateTime dateTime, int days) {
        return dateTime.plusDays(days);
    }

    /**
     * 按天减
     *
     * @param dateTime 时间
     * @param days     天数
     * @return LocalDateTime
     */
    public static LocalDateTime subtractDays(LocalDateTime dateTime, int days) {
        return dateTime.minusDays(days);
    }


    /**
     * 按小时加减
     *
     * @param dateTime 时间
     * @param hours    小时数
     * @return LocalDateTime
     */
    public static LocalDateTime addHours(LocalDateTime dateTime, int hours) {
        return dateTime.plusHours(hours);
    }

    /**
     * 按小时减
     *
     * @param dateTime 时间
     * @param hours    小时数
     * @return LocalDateTime
     */
    public static LocalDateTime subtractHours(LocalDateTime dateTime, int hours) {
        return dateTime.minusHours(hours);
    }

    // 按分钟加减

    /**
     * 按分钟加
     *
     * @param dateTime 时间
     * @param minutes  分钟数
     * @return LocalDateTime
     */
    public static LocalDateTime addMinutes(LocalDateTime dateTime, int minutes) {
        return dateTime.plusMinutes(minutes);
    }

    /**
     * 按分钟减
     *
     * @param dateTime 时间
     * @param minutes  分钟数
     * @return LocalDateTime
     */
    public static LocalDateTime subtractMinutes(LocalDateTime dateTime, int minutes) {
        return dateTime.minusMinutes(minutes);
    }


    /**
     * 按秒加
     *
     * @param dateTime 时间
     * @param seconds  秒数
     * @return LocalDateTime
     */
    public static LocalDateTime addSeconds(LocalDateTime dateTime, int seconds) {
        return dateTime.plusSeconds(seconds);
    }

    /**
     * 按秒减
     *
     * @param dateTime 时间
     * @param seconds  秒数
     * @return LocalDateTime
     */
    public static LocalDateTime subtractSeconds(LocalDateTime dateTime, int seconds) {
        return dateTime.minusSeconds(seconds);
    }

    /**
     * 通用时间加减方法
     *
     * @param dateTime 时间
     * @param amount   整数加  负数减
     * @param unit     ChronoUnit.DAYS 天
     *                 ChronoUnit.HOURS 小时
     *                 ChronoUnit.MINUTES 分钟
     *                 ChronoUnit.SECONDS 秒
     *                 ChronoUnit
     * @return LocalDateTime
     */
    public static LocalDateTime calculateDateTime(LocalDateTime dateTime, long amount, ChronoUnit unit) {
        return dateTime.plus(amount, unit);
    }

    /**
     * 计算两时间相差天数数
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return Long
     */
    public static Long getBetweenDays(LocalDateTime startTime, LocalDateTime endTime) {
        return Duration.between(startTime, endTime).toDays();
    }

    /**
     * 计算两时间相差小时数
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return Long
     */
    public static Long getBetweenHours(LocalDateTime startTime, LocalDateTime endTime) {
        return Duration.between(startTime, endTime).toHours();
    }

    /**
     * 计算两时间相差分钟数
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return Long
     */
    public static Long getBetweenMinutes(LocalDateTime startTime, LocalDateTime endTime) {
        return Duration.between(startTime, endTime).toMinutes();
    }

    /**
     * 计算两时间相差秒数
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return Long
     */
    public static Long getBetweenSeconds(LocalDateTime startTime, LocalDateTime endTime) {
        return ChronoUnit.SECONDS.between(startTime, endTime);

    }

    /**
     * 计算两时间相差毫秒数
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return Long
     */
    public static Long getBetweenMillis(LocalDateTime startTime, LocalDateTime endTime) {
        return Duration.between(startTime, endTime).toMillis();
    }

    /**
     * 计算两时间相差纳秒数
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return Long
     */
    public static Long getBetweenNanos(LocalDateTime startTime, LocalDateTime endTime) {
        return Duration.between(startTime, endTime).toNanos();
    }

    /**
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param unit      ChronoUnit.DAYS 天
     *                  ChronoUnit.HOURS 小时
     *                  ChronoUnit.MINUTES 分钟
     *                  ChronoUnit.SECONDS 秒
     *                  ChronoUnit
     * @return
     */
    public static long getDurationBetween(LocalDateTime startTime, LocalDateTime endTime, ChronoUnit unit) {
        return unit.between(startTime, endTime);
    }


    /**
     * 判断两个时间是否相等
     *
     * @param startTime  开始时间
     * @param endTime    结束时间
     * @param targetTime 时间
     * @return true | false 之间或等于它们时,才返回 true,否则返回 false
     */
    public static boolean isWithinRange(LocalDateTime startTime, LocalDateTime endTime, LocalDateTime targetTime) {
        return (targetTime.isEqual(startTime) || targetTime.isAfter(startTime)) &&
                (targetTime.isEqual(endTime) || targetTime.isBefore(endTime));
    }

    /**
     * 判断一个时间是否早于另一个时间
     *
     * @param time1 LocalDateTime
     * @param time2 LocalDateTime
     * @return 如果 time1 在 time2 之前,否则返回 false
     */
    public static boolean isEarlier(LocalDateTime time1, LocalDateTime time2) {
        return time1.isBefore(time2);
    }

    /**
     * 判断一个时间是否晚于另一个时间
     *
     * @param time1 LocalDateTime
     * @param time2 LocalDateTime
     * @return 如果 time1 在 time2 之后,否则返回 false
     */
    public static boolean isLater(LocalDateTime time1, LocalDateTime time2) {
        return time1.isAfter(time2);
    }

    /**
     * 判断两个时间是否相同
     *
     * @param time1 LocalDateTime
     * @param time2 LocalDateTime
     * @return 如果 time1 , time2 相等,否则返回 false
     */
    public static boolean isSame(LocalDateTime time1, LocalDateTime time2) {
        return time1.isEqual(time2);
    }

    /**
     * 天转小时
     *
     * @param days 天数
     * @return 小时数
     */
    public static long daysToHours(long days) {
        return Duration.ofDays(days).toHours();
    }

    /**
     * 天转分钟
     *
     * @param days 天数
     * @return 分钟数
     */
    public static long daysToMinutes(long days) {
        return Duration.ofDays(days).toMinutes();
    }

    /**
     * 天转秒
     *
     * @param days 天数
     * @return 秒数
     */
    public static long daysToSeconds(long days) {
        return Duration.ofDays(days).getSeconds();
    }

    /**
     * 小时转分钟
     *
     * @param hours 小时
     * @return 分钟
     */
    public static long hoursToMinutes(long hours) {
        return Duration.ofHours(hours).toMinutes();
    }

    /**
     * 小时转秒
     *
     * @param hours 小时
     * @return 秒
     */
    public static long hoursToSeconds(long hours) {
        return Duration.ofHours(hours).getSeconds();
    }

    /**
     * 分钟转秒
     *
     * @param minutes 分钟
     * @return 秒
     */
    public static long minutesToSeconds(long minutes) {
        return Duration.ofMinutes(minutes).getSeconds();
    }

    /**
     * 获取当前时区
     *
     * @return
     */
    public static ZoneId getCurrentTimeZone() {
        return ZoneId.systemDefault();
    }

    /**
     * 获取当前时区的时间
     *
     * @return
     */
    public static ZonedDateTime getCurrentTimeInTimeZone() {
        return ZonedDateTime.now(getCurrentTimeZone());
    }

    /**
     * @param localDateTime time
     * @param fromZone      ZoneId.of("时区")
     * @param toZone        ZoneId.of("时区")
     * @return ZonedDateTime
     */
    public static ZonedDateTime convertTimeZone(LocalDateTime localDateTime, ZoneId fromZone, ZoneId toZone) {
        // 将 LocalDateTime 转换为 ZonedDateTime(起始时区)
        ZonedDateTime fromZonedDateTime = ZonedDateTime.of(localDateTime, fromZone);
        // 将 ZonedDateTime 转换为目标时区的时间
        return fromZonedDateTime.withZoneSameInstant(toZone);
    }


    /**
     * 获取某年的第一天
     *
     * @param year
     * @return
     */
    public static LocalDate getFirstDayOfYear(int year) {
        return LocalDate.of(year, 1, 1);
    }

    /**
     * 获取某年的最后一天
     *
     * @param year
     * @return
     */
    public static LocalDate getLastDayOfYear(int year) {
        return LocalDate.of(year, 12, 31);
    }

    /**
     * 获取某个月的第一天
     *
     * @param year  年
     * @param month 月
     * @return
     */
    public static LocalDate getFirstDayOfMonth(int year, int month) {
        return LocalDate.of(year, month, 1);
    }

    /**
     * 获取某个月的最后一天
     *
     * @param year  年
     * @param month 月
     * @return
     */
    public static LocalDate getLastDayOfMonth(int year, int month) {
        YearMonth yearMonth = YearMonth.of(year, month);
        return yearMonth.atEndOfMonth();
    }

    /**
     * 判断是否是闰年
     *
     * @param year 年
     * @return
     */
    public static boolean isLeapYear(int year) {
        return Year.of(year).isLeap();
    }

    /**
     * 获取一年中某个日期是第几天
     *
     * @param date 年
     * @return
     */
    public static int getDayOfYear(LocalDate date) {
        return date.getDayOfYear();
    }

    /**
     * 获取日期是星期几
     *
     * @param date
     * @return
     */
    public static String getDayOfWeek(LocalDate date) {
        DayOfWeek dayOfWeek = date.getDayOfWeek();
        return dayOfWeek.getDisplayName(
                TextStyle.FULL, // 使用完整的星期几名称
                Locale.CHINESE); // 指定语言为中文
    }

    /**
     * 获取当前日期的本周一的日期
     *
     * @param currentDate
     * @return
     */
    public static LocalDate getMondayOfWeek(LocalDate currentDate) {
        // 获取当前日期的星期几
        DayOfWeek dayOfWeek = currentDate.getDayOfWeek();
        // 计算需要减去的天数,1表示星期一
        int daysToSubtract = dayOfWeek.getValue() - DayOfWeek.MONDAY.getValue();
        // 返回本周一的日期
        return currentDate.minusDays(daysToSubtract);
    }

    /**
     * 获取当前日期所在周的最后一天(周日)的日期
     *
     * @param currentDate
     * @return
     */
    public static LocalDate getLastDayOfWeek(LocalDate currentDate) {
        // 获取当前日期的星期几
        DayOfWeek dayOfWeek = currentDate.getDayOfWeek();
        // 计算需要增加的天数,7表示一周的天数
        int daysToAdd = DayOfWeek.SUNDAY.getValue() - dayOfWeek.getValue();
        // 返回本周最后一天(周日)的日期
        return currentDate.plusDays(daysToAdd);
    }


    /**
     * LocalDate 转换为 LocalDateTime
     *
     * @param time LocalDate
     * @return LocalDateTime
     */
    public static LocalDateTime convertlocalDateToLocalDateTime(LocalDate time) {
        return time.atStartOfDay();
    }

    /**
     * LocalDateTime 转换为 LocalDate
     *
     * @param time LocalDateTime
     * @return LocalDate
     */
    public static LocalDate convertLocalDateTimeToLocalDate(LocalDateTime time) {
        return time.toLocalDate();
    }

    /**
     * LocalDateTime 转换为 Date
     *
     * @param time LocalDateTime
     * @return Date
     */
    public static Date convertLocalDateTimeToDate(LocalDateTime time) {

        return Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * Date  转换为 LocalDateTime
     *
     * @param date Date
     * @return LocalDateTime
     */
    public static LocalDateTime convertDateToLocalDateTime(Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    /**
     * Date 转换为 LocalDate
     *
     * @param dateToConvert Date
     * @return LocalDate
     */
    public static LocalDate convertDateToLocalDate(Date dateToConvert) {
        return dateToConvert.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
    }

    /**
     * LocalDate 转换为 Date
     *
     * @param dateToConvert LocalDate
     * @return Date
     */
    public static Date convertLocalDateToDate(LocalDate dateToConvert) {
        LocalDateTime localDateTime = dateToConvert.atStartOfDay();
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值