Java Date时间工具类

package com.yryc.safe.util;

import cn.hutool.core.util.StrUtil;
import io.swagger.models.auth.In;
import org.apache.taglibs.standard.tag.common.xml.ParseSupport;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;


public class DateUtils {

    // 判断当前页是那个季节
    public static Map<String, String> getQuarter(String date) {
        String year = date.substring(0, 4);
        String month = date.substring(5);
        Map<String, String> map = new HashMap<>();
        if (month != null) {
            if ("01".equals(month) || "02".equals(month) || "03".equals(month)) {
                map.put("startTime", year + "-01");
                map.put("endTime", year + "-03");
            } else if ("04".equals(month) || "05".equals(month) || "06".equals(month)) {
                map.put("startTime", year + "-04");
                map.put("endTime", year + "-06");
            } else if ("07".equals(month) || "08".equals(month) || "09".equals(month)) {
                map.put("startTime", year + "-07");
                map.put("endTime", year + "-09");
            } else if ("10".equals(month) || "11".equals(month) || "12".equals(month)) {
                map.put("startTime", year + "-10");
                map.put("endTime", year + "-12");
            }
        }
        return map;
    }

//    public static QueryDTO getDate(QueryDTO queryDTO){
//        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString();
//        if (queryDTO.getDate().isEmpty()) {
//            // 时间为空默认为上个月数据
//            date = getMonther(date);
//            queryDTO.setDate(date);
//        }
//        return queryDTO;
//    }


    public static String getLastYear(String time) { //获取前年
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy");
            Date days = format.parse(time);
            Calendar c = Calendar.getInstance();
            c.setTime(days);
            c.add(Calendar.YEAR, -1);
            Date d = c.getTime();
            String lastYear = format.format(d);
            return lastYear;
        } catch (Exception e) {
            e.printStackTrace();
            return "时间解析错误";
        }
    }

    public static String getLastYearDay(String time) { //获取前年同一天
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date days = format.parse(time);
            Calendar c = Calendar.getInstance();
            c.setTime(days);
            c.add(Calendar.YEAR, -1);
            Date d = c.getTime();
            String lastYear = format.format(d);
            return lastYear;
        } catch (Exception e) {
            e.printStackTrace();
            return "时间解析错误";
        }
    }

    public static String getDay(String time) { //年-月-日  获取昨天
        try {
            SimpleDateFormat formates = new SimpleDateFormat("yyyy-MM-dd");
            Date dayes = formates.parse(time);
            Calendar cd = Calendar.getInstance();
            cd.setTime(dayes);
            cd.add(Calendar.DAY_OF_WEEK, -1);
            Date des = cd.getTime();
            String ends = formates.format(des);
            return ends;
        } catch (Exception e) {
            e.printStackTrace();
            return "时间解析错误";
        }
    }

    public static String getTomorrowDay(String time) { //年-月-日  获取明天
        try {
            SimpleDateFormat formates = new SimpleDateFormat("yyyy-MM-dd");
            Date dayes = formates.parse(time);
            Calendar cd = Calendar.getInstance();
            cd.setTime(dayes);
            cd.add(Calendar.DAY_OF_WEEK, +1);
            Date des = cd.getTime();
            String ends = formates.format(des);
            return ends;
        } catch (Exception e) {
            e.printStackTrace();
            return "时间解析错误";
        }
    }


    public static String getDay3(Date dayes) { //年-月-日  获取昨天
        try {
            SimpleDateFormat formates = new SimpleDateFormat("yyyy-MM-dd");
            Calendar cd = Calendar.getInstance();
            cd.setTime(dayes);
            cd.add(Calendar.DAY_OF_WEEK, -1);
            Date des = cd.getTime();
            String ends = formates.format(des);
            return ends;
        } catch (Exception e) {
            e.printStackTrace();
            return "时间解析错误";
        }
    }

    public static String getDay2(String time) { //年-月-日  获取昨天
        try {
            SimpleDateFormat formates = new SimpleDateFormat("yyyy-MM-dd HH");
            Date dayes = formates.parse(time);
            Calendar cd = Calendar.getInstance();
            cd.setTime(dayes);
            cd.add(Calendar.DAY_OF_WEEK, -1);
            Date des = cd.getTime();
            String ends = formates.format(des);
            return ends;
        } catch (Exception e) {
            e.printStackTrace();
            return "时间解析错误";
        }
    }


    public static String getSameDayLastYear(String time) { //年-月  //获取去年同月
        try {
            //去年同月
            SimpleDateFormat formates = new SimpleDateFormat("yyyy-MM");
            Date dayes = formates.parse(time);
            Calendar cd = Calendar.getInstance();
            cd.setTime(dayes);
            cd.add(Calendar.YEAR, -1);
            Date des = cd.getTime();
            String ends = formates.format(des);
            return ends;
        } catch (Exception e) {
            e.printStackTrace();
            return "时间解析错误";
        }
    }

    public static String getMonther(String time) { //年-月  获取上一月
        try {
            SimpleDateFormat formates = new SimpleDateFormat("yyyy-MM");
            Date dayes = formates.parse(time);
            Calendar cd = Calendar.getInstance();
            cd.setTime(dayes);
            cd.add(Calendar.MONTH, -1);
            Date des = cd.getTime();
            String ends = formates.format(des);
            return ends;
        } catch (Exception e) {
            e.printStackTrace();
            return "时间解析错误";
        }
    }


    //字符串转Date
    public static Date StringToDate(String time) {
        try {
            if (StrUtil.isEmpty(time)) {
                return null;
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            return format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Date StringToDate2(String time) {
        try {
            if (StrUtil.isEmpty(time)) {
                return null;
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    //取传入时间往后推7天的时间
    public static String getTenDayBefore(String time) {
        try {
            SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");
            Date nowDate = sm.parse(time);
            Calendar calendar = Calendar.getInstance();
            //往前推10天
            calendar.setTime(nowDate);
            calendar.add(Calendar.DATE, 6);
            return sm.format(calendar.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

    //Date转字符串
    public static String dateToString(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }


    //Date转字符串
    public static String dateToStringYYYY(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        return sdf.format(date);
    }

    //Date转字符串
    public static String dateToString2(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

    //Date转字符串
    public static String dateToString3(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");
        return sdf.format(date);
    }

    public static String dateToString4(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssS");
        return sdf.format(date);
    }


    /**
     * @return
     * @Description : 获取年月
     */
    public static String findYearMonth() {
        int year;
        int month;
        String date;
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH) + 1;
        date = year + "-" + (month < 10 ? "0" + month : month);
        return date;

    }


    /**
     * @return
     * @Description : 获取上个月
     */
    public static String findYearMonth2() {
        int year;
        int month;
        String date;
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH);
        date = year + "-" + (month < 10 ? "0" + month : month);
        return date;

    }

    /**
     * 获取本月倒数第三天
     *
     * @return
     */
    public static String getLastThree() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, 1);
        calendar.set(Calendar.DATE, 1);
        calendar.add(Calendar.DATE, -3);
        Date theDate = calendar.getTime();
        String s = df.format(theDate);
        return s;
    }


    //获取下一个月的今天
    public static String getNextMonthDay(String time) {
        //时间字符串转 LocalDate 类型
        LocalDate today = LocalDate.parse(time);
        //当前月份+(-1)
        today = today.minusMonths(-1);
        //LocalDate日期格式是"YYYY-MM-DD",只需要用toString()就可以转化成字符串类型
        return today.toString();
    }


    /**
     * 获取指定时间的前一个月日期
     *
     * @param date
     * @return
     */
    public static Date getLastDate(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, -1);
        return cal.getTime();
    }

    /**
     * 根据当前时间获取当前年第几周
     *
     * @return
     */
    public static int getCircumference() {

        Calendar calendar = Calendar.getInstance();
        //设置星期一为一周开始的第一天
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        //获得当前的时间戳
        calendar.setTimeInMillis(System.currentTimeMillis());
        //获得当前日期属于今年的第几周
        int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
        return weekOfYear;
    }

    /**
     * 根据当前时间获取当前年有几周
     *
     * @return
     */
    public static int getCircumferenceSum() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        Calendar mCalendar = new GregorianCalendar(TimeZone.getDefault());
        mCalendar.setFirstDayOfWeek(Calendar.MONDAY);
        // Workaround
        mCalendar.set(year,
                Calendar.DECEMBER,
                31);
        int totalDaysInYear = mCalendar.get(Calendar.DAY_OF_YEAR);
        System.out.println(totalDaysInYear);
        int totalWeeks = totalDaysInYear / 7;
        int sum = totalWeeks * 7;
        int daySum = totalDaysInYear - sum;
        if (daySum >= 1) {
            totalWeeks = totalWeeks + 1;
        }
        System.out.println(totalWeeks);
        return totalWeeks;
    }

    /**
     * 根据当前数字返回周几
     *
     * @return
     */
    public static String getWeekByNumber(String value) {
        if (value.equals("1")) {
            return "周一";
        }

        if (value.equals("2")) {
            return "周二";
        }

        if (value.equals("3")) {
            return "周三";
        }

        if (value.equals("4")) {
            return "周四";
        }

        if (value.equals("5")) {
            return "周五";
        }

        if (value.equals("6")) {
            return "周六";
        }

        if (value.equals("0")) {
            return "周日";
        }
        return "";
    }


    public static String sscToString(long value) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(value);
    }


    // 补齐期间年份
    public static List<String> completeYears(String startYearStr, String endYearStr) {
        // 将字符串转换为整数年份
        int startYear = Integer.parseInt(startYearStr);
        int endYear = Integer.parseInt(endYearStr);

        // 创建一个列表来存储所有年份
        List<String> years = new ArrayList<>();

        // 循环遍历年份范围,包括起始和结束年份
        for (int year = startYear; year <= endYear; year++) {
            // 将年份添加到列表中
            years.add(String.valueOf(year));
        }

        // 返回补齐的年份列表
        return years;
    }

    public static String getOneYearLater(String time) {
        try {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            // 将当前字符串时间解析为 Date 对象
            Date currentDate = sdf.parse(time);
            calendar.setTime(currentDate);

            // 往后推迟一年
            calendar.add(Calendar.YEAR, 1);

            // 获取一年后的时间
            Date oneYearLater = calendar.getTime();
            String oneYearLaterString = sdf.format(oneYearLater);

            return oneYearLaterString;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getOneYear(String time) {
        try {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 将当前字符串时间解析为 Date 对象
            Date currentDate = sdf.parse(time);
            calendar.setTime(currentDate);

            // 往后推迟一年
            calendar.add(Calendar.YEAR, 1);

            // 获取一年后的时间
            Date oneYearLater = calendar.getTime();
            String oneYearLaterString = sdf.format(oneYearLater);

            return oneYearLaterString;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 比较两个时间大小
     *
     * @param dateStr1
     * @param dateStr2
     * @return
     */
    public static boolean isDateBefore(String dateStr1, String dateStr2) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date1 = sdf.parse(dateStr1);
            Date date2 = sdf.parse(dateStr2);
            return date1.before(date2);
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static String getExcelTime(String time) {
        // 定义序列号
        int serialNumber = Integer.parseInt(time);

// 将序列号转换为Date对象
        Calendar calendar = Calendar.getInstance();
        calendar.set(1900, Calendar.JANUARY, 1); // 设置为Excel的起始日期

        calendar.add(Calendar.DATE, serialNumber - 2); // Excel的序列号从1开始,因此要减去2天

        Date date = calendar.getTime();

// 将Date对象转换为字符串
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = dateFormat.format(date);

        System.out.println(dateString);
        return dateString;
    }

    public static String getDaySubtract(Date currentDate, int sum) {
        // 获取前七天的日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        calendar.add(Calendar.DAY_OF_MONTH, sum);
        Date sevenDaysAgo = calendar.getTime();

        // 格式化日期为字符串
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        return formatter.format(sevenDaysAgo);
    }

    /**
     * 获取当前时间减去几分钟的时间
     */
    public static String getTimeSubtractMinute(int minute) {
        Date currentDate = new Date(); // 当前时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        // 将当前时间减去一分钟
        calendar.add(Calendar.MINUTE, -minute);
        Date previousMinute = calendar.getTime(); // 前一分钟时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(previousMinute);
    }

    public static boolean isDifferenceWithin5Minutes(Date date1, Date date2) {
        long difference = Math.abs(date1.getTime() - date2.getTime());
        return difference <= 300000; // 5分钟的毫秒数
    }

    // 将数字转换为中文大写
    public static String convertToChineseNumber(int number) {
        StringBuilder chineseNumber = new StringBuilder();
        String numberStr = String.valueOf(number);
        String[] CHINESE_NUMBERS = {"〇", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
        for (int i = 0; i < numberStr.length(); i++) {
            int digit = Character.getNumericValue(numberStr.charAt(i));
            chineseNumber.append(CHINESE_NUMBERS[digit]);
        }
        return chineseNumber.toString();
    }

    public static String getDadeZw() {
        LocalDate currentDate = LocalDate.now();
        int year = currentDate.getYear();
        int month = currentDate.getMonthValue();
        int day = currentDate.getDayOfMonth();

        String chineseYear = convertToChineseNumber(year);
        String chineseMonth = convertToChineseNumber(month);
        String chineseDay = convertToChineseNumber(day);
        return chineseYear + "年" + chineseMonth + "月" + chineseDay + "日";
    }

    public static Long getNumberDays(String startTime,String endTime) {
        // 将字符串转换为LocalDateTime对象
//        LocalDateTime findDateTime = LocalDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//        LocalDateTime timeDateTime = LocalDateTime.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//
//        // 计算时间差异
//        long daysDiff = ChronoUnit.DAYS.between(findDateTime, timeDateTime);

        startTime = startTime.substring(0,10);
        endTime = endTime.substring(0,10);

        // 将字符串转换为LocalDate对象
        LocalDate findDate = LocalDate.parse(startTime);
        LocalDate timeDate = LocalDate.parse(endTime);

        // 计算日期差异
        long daysDiff = ChronoUnit.DAYS.between(findDate, timeDate);
        return daysDiff;
    }


    public static Map<String,String> getRegionTime(String time,String type) {//type 1-周 2-月 3-年
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, String> map = new HashMap<>();
        try {
            Date date = sdf.parse(time);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            if (type.equals("1")){
                // 获取周的开始时间和结束时间(从周一到周日)
                calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
                String weekStartDate = sdf.format(calendar.getTime());
                calendar.add(Calendar.DAY_OF_WEEK, 6);
                String weekEndDate = sdf.format(calendar.getTime());
                map.put("startTime",weekStartDate);
                map.put("endTime",weekEndDate);
            } else if (type.equals("2")){
                // 获取月的开始时间和结束时间
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                String monthStartDate = sdf.format(calendar.getTime());
                calendar.add(Calendar.MONTH, 1);
                calendar.add(Calendar.DAY_OF_MONTH, -1);
                String monthEndDate = sdf.format(calendar.getTime());
                map.put("startTime",monthStartDate);
                map.put("endTime",monthEndDate);
            } else if (type.equals("3")){
                // 获取年的开始时间和结束时间
                calendar.set(Calendar.DAY_OF_YEAR, 1);
                String yearStartDate = sdf.format(calendar.getTime());
                calendar.add(Calendar.YEAR, 1);
                calendar.add(Calendar.DAY_OF_YEAR, -1);
                String yearEndDate = sdf.format(calendar.getTime());
                map.put("startTime",yearStartDate);
                map.put("endTime",yearEndDate);
            }
            return map;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }


    // 统计今年过了多少天
    public static Integer getDays(){
        // 获取当前日期
        LocalDate now = LocalDate.now();

        // 获取今年的第一天
        int year = now.getYear();
        LocalDate firstDayOfYear = LocalDate.of(year, 1, 1);

        // 计算今年过了多少天
        long daysPassed = ChronoUnit.DAYS.between(firstDayOfYear, now);

        System.out.println("今年过了 " + daysPassed + " 天");

        return Integer.parseInt(String.valueOf(daysPassed));
    }

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值