个人总结的日期类文件 DateUtil

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * 日期处理
 */
public class DateUtils {
    /**
     * 时间格式(yyyy-MM-dd)
     */
    public final static String DATE_PATTERN = "yyyy-MM-dd";
    public final static String DATE_PATTERN_yyyyMMdd = "yyyyMMdd";
    public final static String DATE_PATTERN_yyyyMM = "yyyyMM";
    /**
     * 时间格式(yyyy-MM-dd HH:mm:ss)
     */
    public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public final static String DATE_TIME_PATTERN_SSS = "yyyy-MM-dd HH:mm:ss.SSS";
    public final static String DATE_TIME_PATTERN_T_SSS = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
    /**
     * 时间格式(yyyyMMddHHmmss)
     */
    public final static String DATE_TIME_PATTERN_yyyymmddhhmmss = "yyyyMMddHHmmss";

    /**
     * 日期格式化 日期格式为:yyyy-MM-dd
     *
     * @param date 日期
     * @return 返回yyyy-MM-dd格式日期
     */
    public static String format(Date date) {
        return format(date, DATE_PATTERN);
    }

    public static String formatStringZToString(String date) {
        Date dd = parse(date, DateUtils.DATE_TIME_PATTERN_T_SSS);
        return format(dd, DateUtils.DATE_TIME_PATTERN);
    }

    /**
     * 日期格式化 日期格式为:yyyy-MM-dd
     *
     * @param date    日期
     * @param pattern 格式,如:DateUtils.DATE_TIME_PATTERN
     * @return 返回yyyy-MM-dd格式日期
     */
    public static String format(Date date, String pattern) {
        if (date != null) {
            SimpleDateFormat df = new SimpleDateFormat(pattern);
            return df.format(date);
        }
        return null;
    }

    /**
     * 日期解析
     *
     * @param date    日期
     * @param pattern 格式,如:DateUtils.DATE_TIME_PATTERN
     * @return 返回Date
     */
    public static Date parse(String date, String pattern) {
        if (StringUtils.isEmpty(date)) {
            return null;
        }
        try {
            return new SimpleDateFormat(pattern).parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 字符串转换成日期
     *
     * @param strDate 日期字符串
     * @param pattern 日期的格式,如:DateUtils.DATE_TIME_PATTERN
     */
    public static Date stringToDate(String strDate, String pattern) {
        if (StringUtils.isBlank(strDate)) {
            return null;
        }

        DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
        return fmt.parseLocalDateTime(strDate).toDate();
    }

    /**
     * 根据周数,获取开始日期、结束日期
     *
     * @param week 周期  0本周,-1上周,-2上上周,1下周,2下下周
     * @return 返回date[0]开始日期、date[1]结束日期
     */
    public static Date[] getWeekStartAndEnd(int week) {
        DateTime dateTime = new DateTime();
        LocalDate date = new LocalDate(dateTime.plusWeeks(week));

        date = date.dayOfWeek().withMinimumValue();
        Date beginDate = date.toDate();
        Date endDate = date.plusDays(6).toDate();
        return new Date[]{beginDate, endDate};
    }

    /**
     * 对日期的【秒】进行加/减
     *
     * @param date    日期
     * @param seconds 秒数,负数为减
     * @return 加/减几秒后的日期
     */
    public static Date addDateSeconds(Date date, int seconds) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusSeconds(seconds).toDate();
    }

    /**
     * 对日期的【分钟】进行加/减
     *
     * @param date    日期
     * @param minutes 分钟数,负数为减
     * @return 加/减几分钟后的日期
     */
    public static Date addDateMinutes(Date date, int minutes) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusMinutes(minutes).toDate();
    }

    /**
     * 对日期的【小时】进行加/减
     *
     * @param date  日期
     * @param hours 小时数,负数为减
     * @return 加/减几小时后的日期
     */
    public static Date addDateHours(Date date, int hours) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusHours(hours).toDate();
    }

    /**
     * 对日期的【天】进行加/减
     *
     * @param date 日期
     * @param days 天数,负数为减
     * @return 加/减几天后的日期
     */
    public static Date addDateDays(Date date, int days) {
        if (null == date) {
            return null;
        }
        DateTime dateTime = new DateTime(date);
        return dateTime.plusDays(days).toDate();
    }

    /**
     * 对日期的【周】进行加/减
     *
     * @param date  日期
     * @param weeks 周数,负数为减
     * @return 加/减几周后的日期
     */
    public static Date addDateWeeks(Date date, int weeks) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusWeeks(weeks).toDate();
    }

    /**
     * 对日期的【月】进行加/减
     *
     * @param date   日期
     * @param months 月数,负数为减
     * @return 加/减几月后的日期
     */
    public static Date addDateMonths(Date date, int months) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusMonths(months).toDate();
    }

    /**
     * 对日期的【年】进行加/减
     *
     * @param date  日期
     * @param years 年数,负数为减
     * @return 加/减几年后的日期
     */
    public static Date addDateYears(Date date, int years) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusYears(years).toDate();
    }

    /**
     * 将时间戳转为时间格式 字符串返回
     *
     * @param time 单位秒
     * @return
     */
    public static String getTimestampSecondToStrDate(long time) {
        return getTimestampToStrDate(time * 1000);
    }

    /**
     * 将时间戳转为时间格式 字符串返回
     *
     * @param time 单位秒
     * @return
     */
    public static String getTimestampToStrDate(long time) {
        return format(new Date(time), DATE_TIME_PATTERN);
    }

    /**
     * 返回当前日期
     *
     * @return
     */
    public static Date getCurrentDate() {
        return new Date();
    }

    /**
     * 获取当前时间 格式:yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public static String getCurrentDateSS() {
        return format(new Date(), DATE_TIME_PATTERN);
    }

    /**
     * 获取当前时间 格式:yyyyMMddHHmmss
     *
     * @return
     */
    public static String getCurrentDateyyyyMMddHHmmss() {
        return format(new Date(), DATE_TIME_PATTERN_yyyymmddhhmmss);
    }

    /**
     * 本地时间转为UTC yyyy-MM-dd HH:mm:ss  并分成两个高低位
     *
     * @return 单位 秒
     */
    public static short[] localToUTCDivTwo(Date date) {
        Date localTime = date;
        if (null == localTime) {
            localTime = DateUtils.getCurrentDate();
        }
        short[] data = new short[2];
        try {
            Long d = getUtcTimeDate(localTime);
            if (null == d) {
                return data;
            }
            String ss = Long.toBinaryString(d);
            if (ss.length() <= 16) {
                data[0] = 0;
                data[1] = Short.parseShort(d + "");
            } else {
                String high = ss.substring(0, ss.length() - 16);
                String low = ss.substring(ss.length() - 16);
                data[0] = (short) Integer.parseInt(high, 2);
                data[1] = (short) Integer.parseInt(low, 2);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    public static long getUtcTimeLocal() {
        // 获取现在的LocalDateTime 时间
        LocalDateTime localDateTime = LocalDateTime.now();
        // 转为TimeStamp类型
        Timestamp timestamp = Timestamp.valueOf(localDateTime.atZone(ZoneId.systemDefault())
                .toOffsetDateTime()
                .withOffsetSameInstant(ZoneOffset.UTC)
                .toLocalDateTime());
        // 获取时间戳
        return timestamp.getTime() / 1000;
    }

    public static long getUtcTimeDate(Date date) {
        return date.getTime() / 1000;
    }

    /**
     * UTC时间戳 转为本地时间
     *
     * @param times 秒
     * @return
     */
    public static Date utc2Local(Long times) {
        if (null == times) {
            return null;
        }
        Date dd = new Date(times * 1000);
        return dd;
    }

    /**
     * UTC时间戳 转为本地时间
     *
     * @param times 毫秒
     * @return
     */
    public static Date utc2LocalMS(Long times) {
        if (null == times) {
            return null;
        }
        Date dd = new Date(times);
        return dd;
    }

    /**
     * 线程延迟时间
     *
     * @param time
     */
    public static void threadDelayTime(long time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
        }
    }

    /**
     * 计算两个日期之间相差的天数
     *
     * @param smdate 较小的时间
     * @param bdate  较大的时间
     * @return 相差天数
     * @throws ParseException
     */
    public static int daysBetween(Date smdate, Date bdate) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            smdate = sdf.parse(sdf.format(smdate));
            bdate = sdf.parse(sdf.format(bdate));
            Calendar cal = Calendar.getInstance();
            cal.setTime(smdate);
            long time1 = cal.getTimeInMillis();
            cal.setTime(bdate);
            long time2 = cal.getTimeInMillis();
            long between_days = (time2 - time1) / (1000 * 3600 * 24);

            return Integer.parseInt(String.valueOf(between_days));
        } catch (Exception e) {

        }
        return 0;
    }

    /**
     * @param second 秒
     * @description: 秒转换为时分秒 HH:mm:ss 格式 仅当小时数大于0时 展示HH
     * @return: {@link String}
     * @author: wwg
     * @date: 2023-2-02 13:55:17
     */
    public static String second2Time(Long second) {
        if (second == null || second < 0) {
            return "00:00:00";
        }

        long h = second / 3600;
        long m = (second % 3600) / 60;
        long s = second % 60;
        String str = "";
        if (h > 0) {
            str = (h < 10 ? ("0" + h) : h) + ":";
        } else {
            str = "00:";
        }
        str += (m < 10 ? ("0" + m) : m) + ":";
        str += (s < 10 ? ("0" + s) : s);
        return str;

    }

    /**
     * 将时间戳 改为时间
     *
     * @param deviceSamplingTime
     * @return
     */
    public static Date getTimestampToDate(String deviceSamplingTime) {
        if (StringUtils.isEmpty(deviceSamplingTime)) {
            return null;
        }
        return new Date(Long.parseLong(deviceSamplingTime));
    }

    public static Date parseObjectTime(Object startTime) {
        if (null == startTime) {
            return null;
        }
        return parse(startTime.toString(), DATE_TIME_PATTERN);
    }

    /**
     * 获取周的 周一时间 周二时间
     * @param date
     * @return
     */
    public static Date[] getWeekStartAndEndTimes(Date date) {
        Date[] times = new Date[2];
        if (null == date) {
            date = getCurrentDate();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        // 7 为周6 周日 为 1
        int a = calendar.get(Calendar.DAY_OF_WEEK) - 2;
        //获取周一时间
        calendar.add(Calendar.DAY_OF_YEAR, a < 0 ? -6 : -a);
        times[0] = calendar.getTime();

        //周日时间
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.add(Calendar.DAY_OF_YEAR, 6);
        times[1] = calendar.getTime();
        return times;
    }

    /**
     * 获取当月的开始时间结束时间
     * @param date
     * @return
     */
    public static Date[] getMonthStartAndEndTimes(Date date) {
        Date[] times = new Date[2];
        if (null == date) {
            date = getCurrentDate();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        // 7 为周6 周日 为 1
        int a = calendar.get(Calendar.DAY_OF_MONTH);
        //获取月初时间
        calendar.add(Calendar.DAY_OF_YEAR, 1 - a);
        times[0] = calendar.getTime();

        //周日时间
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.add(Calendar.DAY_OF_YEAR, lastDay - 1);

        times[1] = calendar.getTime();
        return times;
    }


    /**
     * 获取当天的开始结束时间
     * @param date
     * @return
     */
    public static Date[] getDayStartAndEndTimes(Date date) {
        Date[] times = new Date[2];
        if (null == date) {
            date = getCurrentDate();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        times[0] = calendar.getTime();

        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        times[1] = calendar.getTime();
        return times;
    }


    public static void main(String[] args) {
        System.out.println(getWeekStartAndEndTimes(null)[0] );
        System.out.println(getWeekStartAndEndTimes(null)[1] );
    }
}

你可能感兴趣的:(java)