Java localdatetime date localdate 实用的日期工具类 字符串转日期 获取两个日期包含的所有日期等等......

废话不多说,直接上代码,可以直接拷贝使用,基本都有注释说明,很容易就找到自己想要的

 

package com.rocky.fintech.boss.util;


import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author zhangyi
 * @date 2019/10/17
 */
public class DateUtils {

    public static final String FORMAT_1 = "yyyy-MM-dd";
    public static final String FORMAT_2 = "yyyy-MM-dd HH:mm:ss";
    public static final String FORMAT_3 = "yyyy-MM-dd HH:mm";

    public static final String FORMAT_4 = "yyyy年MM月dd日";

    public static final String FORMAT_5 = "yyyyMMddHHmmss";

    public static final String FORMAT_6 = "MM-dd";
    public static final String FORMAT_7 = "HH:mm";

    public static final String FORMAT_8 = "yyyyMMdd";
    public static final String FORMAT_9 = "HHmmss";

    public static final String FORMAT_10 = "yyyy";
    public static final String FORMAT_11 = "yyyy-MM-dd HH:mm:ss.SSS";
    public static final String FORMAT_12 = "yyyy-MM";

    public static final String FORMAT_13 = "HH";
    public static final String FORMAT_14 = "dd";

    public static final String FORMAT_15 = "yyyy-MM-dd HH";

    public static DateTimeFormatter DATE_FORMAT_9 = DateTimeFormatter.ofPattern("HHmmss");
    public static DateTimeFormatter DATE_FORMAT_10 = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");
    public static DateTimeFormatter DATE_FORMAT_11 = DateTimeFormatter.ofPattern("MM/dd/yyyy");

    public static DateTimeFormatter DATE_FORMAT_20 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    public static DateTimeFormatter DATE_FORMAT_21 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    public static DateTimeFormatter DATE_FORMAT_23 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    public static DateTimeFormatter DATE_FORMAT_24 = DateTimeFormatter.ofPattern("yyyy-MM");

    public static DateTimeFormatter DATE_FORMAT_30 = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    public static DateTimeFormatter DATE_FORMAT_31 = DateTimeFormatter.ofPattern("yyyyMMdd");
    public static DateTimeFormatter DATE_FORMAT_32 = DateTimeFormatter.ofPattern("yyyyMM");

    public static DateTimeFormatter DATE_FORMAT_40 = DateTimeFormatter.ofPattern("HH:mm");

    public static DateTimeFormatter DATE_FORMAT_41 = DateTimeFormatter.ofPattern("yyyy.MM.dd");

    public static DateTimeFormatter DATE_FORMAT_42 = DateTimeFormatter.ofPattern("yyyy年MM月");

    public static DateTimeFormatter DATE_FORMAT_43 = DateTimeFormatter.ofPattern("dd-MM-yy");

    public static final DateTimeFormatter DATE_COMMON_PATTERN = DateTimeFormatter
            .ofPattern("[yyyy-MM-dd[ HH:mm:ss]][yyyyMMdd]");

    /**
     * 字符串转日期
     */
    public static LocalDate stringToDate(String date) {
        if (StringUtils.isBlank(date)) {
            return null;
        }
        return LocalDate.parse(date, DATE_COMMON_PATTERN);
    }

    /**
     * 字符串转日期
     */
    public static LocalDateTime stringToDateTime(String date, String pattern) {
        if (StringUtils.isBlank(date)) {
            return null;
        }
        return stringToDateTime(date, DateTimeFormatter.ofPattern(pattern));
    }

    /**
     * 转时间戳
     */
    public static long getTimeStamp(LocalDateTime localDateTime) {
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = localDateTime.atZone(zone).toInstant();
        return instant.toEpochMilli();
    }

    /**
     * 字符串转日期
     */
    public static LocalDateTime stringToDateTime(String date, DateTimeFormatter formatter) {
        if (StringUtils.isBlank(date)) {
            return null;
        }
        return formatter.parse(date, temporal -> {
            LocalDate date1 = temporal.isSupported(ChronoField.EPOCH_DAY)
                    ? LocalDate.ofEpochDay(temporal.getLong(ChronoField.EPOCH_DAY))
                    : LocalDate.now();
            LocalTime time = temporal.isSupported(ChronoField.NANO_OF_DAY)
                    ? LocalTime.ofNanoOfDay(temporal.getLong(ChronoField.NANO_OF_DAY))
                    : LocalTime.MIN;
            return LocalDateTime.of(date1, time);
        });
    }

    /**
     * LocalDateTime转Date
     */
    public static Date toDate(LocalDateTime dateTime) {
        if (dateTime == null) {
            return null;
        }
        return Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * LocalDate转Date
     */
    public static Date toDate(LocalDate date) {
        return Date.from(LocalDateTime.of(date, LocalTime.MIN).atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 获取当前国家当前时间
     */
    public static LocalDateTime getCountyTime(int timeDifference) {
        return LocalDateTime.now().plusHours(timeDifference);
    }

    /**
     * cs
     * 获取当前国家时间
     */
    public static LocalDateTime getCountyTime(LocalDateTime date, int timeDifference) {
        return date.plusHours(timeDifference);
    }

    /**
     * 根据出生日期获取年龄
     */
    public static int getAge(LocalDate birthDay) {
        if (birthDay == null) {
            return 0;
        }
        return birthDay.until(LocalDate.now()).getYears();
    }

    /**
     * 根据出生日期获取年龄
     */
    public static int getAge(LocalDateTime birthDay) {
        if (birthDay == null) {
            return 0;
        }
        return birthDay.toLocalDate().until(LocalDate.now()).getYears();
    }

    /**
     * 根据出生日期获取年龄
     */
    public static int getAge(String birthDay) {
        if (StringUtils.isBlank(birthDay)) {
            return 0;
        }
        LocalDate birthDayTime = LocalDate.parse(birthDay, DATE_COMMON_PATTERN);
        return birthDayTime.until(LocalDate.now()).getYears();
    }

    /**
     * 获取指定日期所在周的第一天
     */
    public static String getWeekFirstDay(String date) {
        if (StringUtils.isBlank(date)) {
            return null;
        }
        LocalDate localDate = LocalDate.parse(date, DATE_COMMON_PATTERN);
        LocalDate day = localDate.minusDays(localDate.getDayOfWeek().getValue() - 1);
        return day.format(DATE_FORMAT_23);
    }

    /**
     * 获取指定日期所在周的第一天
     */
    public static String getWeekFirstDay(LocalDate date) {
        if (date == null) {
            return null;
        }
        LocalDate day = date.minusDays(date.getDayOfWeek().getValue() - 1);
        return day.format(DATE_FORMAT_23);
    }

    /**
     * 获取指定日期所在周的最后一天
     */
    public static String getWeekLastDay(String date) {
        if (StringUtils.isBlank(date)) {
            return null;
        }
        LocalDate localDate = LocalDate.parse(date, DATE_COMMON_PATTERN);
        LocalDate day = localDate.plusDays(7 - localDate.getDayOfWeek().getValue());
        return day.format(DATE_FORMAT_23);
    }

    /**
     * 获取指定日期所在周的最后一天
     */
    public static String getWeekLastDay(LocalDate date) {
        if (date == null) {
            return null;
        }
        LocalDate day = date.plusDays(7 - date.getDayOfWeek().getValue());
        return day.format(DATE_FORMAT_23);
    }

    /**
     * 获取指定日期所在月的第一天
     */
    public static String getMonthFirstDate(String date) {
        if (StringUtils.isBlank(date)) {
            return null;
        }
        LocalDate localDate = LocalDate.parse(date, DATE_COMMON_PATTERN);
        LocalDate day = localDate.with(TemporalAdjusters.firstDayOfMonth());
        return day.format(DATE_FORMAT_23);
    }

    /**
     * 获取指定日期所在月的第一天
     */
    public static String getMonthFirstDate(LocalDate date) {
        if (date == null) {
            return null;
        }
        LocalDate day = date.with(TemporalAdjusters.firstDayOfMonth());
        return day.format(DATE_FORMAT_23);
    }

    /**
     * 获取指定日期所在月的最后一天
     */
    public static String getMonthLastDate(String date) {
        if (StringUtils.isBlank(date)) {
            return null;
        }
        LocalDate localDate = LocalDate.parse(date, DATE_COMMON_PATTERN);
        LocalDate day = localDate.with(TemporalAdjusters.lastDayOfMonth());
        return day.format(DATE_FORMAT_23);
    }

    /**
     * 获取指定日期所在月的最后一天
     */
    public static String getMonthLastDate(LocalDate date) {
        if (date == null) {
            return null;
        }
        LocalDate day = date.with(TemporalAdjusters.lastDayOfMonth());
        return day.format(DATE_FORMAT_23);
    }

    public static String timeToString(Date d, String pattern) {
        if (d == null) {
            return null;
        }
        return new SimpleDateFormat(pattern).format(d);
    }

    public static String localDateToString(LocalDate date, String pattern) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pattern);
        return date.format(fmt);
    }

    public static String localDateTimeToString(LocalDateTime date, String pattern) {
        if (date == null) {
            return "";
        }
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pattern);
        return date.format(fmt);
    }

    /**
     * 获取过去或者未来 任意天内的日期数组
     */
    public static ArrayList getDateArr(int intervals) {
        ArrayList pastDaysList = new ArrayList<>();
        for (int i = intervals - 1; i >= 0; i--) {
            pastDaysList.add(getPastDate(i));
        }
        return pastDaysList;
    }

    /**
     * 获取过去第几天的日期
     */
    public static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(today);
    }

    /**
     * 获取未来 第 past 天的日期
     */
    public static String getFetureDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(today);
    }

    /**
     * 获取两个时间段内的所有日期,日期可跨年
     */
    public static List getBetweenDate(String begin, String end) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List betweenList = new ArrayList<>();

        try {
            Calendar startDay = Calendar.getInstance();
            startDay.setTime(format.parse(begin));
            startDay.add(Calendar.DATE, -1);

            while (true) {
                startDay.add(Calendar.DATE, 1);
                Date newDate = startDay.getTime();
                String newend = format.format(newDate);
                betweenList.add(newend);
                if (end.equals(newend)) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return betweenList;
    }

    /**
     * 时间差 type:1天,2,小时,3,分钟,4秒
     */
    public static Long getDateDiff(LocalDateTime currentTime, LocalDateTime compareTime, int type) {
        Long diffTime = null;
        long diff = getTimeStamp(currentTime) - getTimeStamp(compareTime);
        switch (type) {
            case 1:
                diffTime = diff / (1000 * 60 * 60 * 24);
                break;
            case 2:
                diffTime = diff / (1000 * 60 * 60);
                break;
            case 3:
                diffTime = diff / (1000 * 60);
                break;
            case 4:
                diffTime = diff / 1000;
                break;
        }
        return diffTime;
    }

    public static LocalDateTime getDateEndTime(LocalDateTime localDateTime) {
        LocalDate day = localDateTime.toLocalDate();
        return LocalDateTime.of(day.getYear(), day.getMonthValue(), day.getDayOfMonth(), 23, 59, 59);
    }
}

如有疑惑请留言,看到会一一解答。

你可能感兴趣的:(Java后端代码)