当前位置: 首页 > 工具软件 > Dateutils > 使用案例 >

DateUtils工具类

吕钧
2023-12-01
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Author:wangyt
 * @Description:TODO
 * @Date:2019/5/5$
 **/
public class DateUtils {
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private static Calendar startDate = Calendar.getInstance();
    private static Calendar endDate = Calendar.getInstance();
    private static Date earlydate = new Date();
    private static Date latedate = new Date();

    //获取当前年
    public static String getNowYear() {
        Date day = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy");
        return df.format(day);
    }

    //获取当前月
    public static String getNowMonth() {
        Date day = new Date();
        SimpleDateFormat df = new SimpleDateFormat("MM");
        return df.format(day);
    }

    //获取当前日
    public static String getNowDay() {
        Date day = new Date();
        SimpleDateFormat df = new SimpleDateFormat("dd");
        return df.format(day);
    }

    //获取上一个月份
    public static String getLastMonth() {
        Calendar cal = Calendar.getInstance();
        cal.add(cal.MONTH, -1);
        SimpleDateFormat dft = new SimpleDateFormat("MM");
        return dft.format(cal.getTime());
    }

    //获取上一个年份
    public static String getLastYear() {
        String nowYear = getNowYear();
        return String.valueOf(Integer.valueOf(nowYear) - 1);
    }

    //获取上一个年月
    public static String getLastYearMonth() {
        Calendar cal = Calendar.getInstance();
        cal.add(cal.MONTH, -1);
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM");
        return dft.format(cal.getTime());
    }

    //获取系统当前年月(xxxx-xx)
    public static String getNowDate() {
        Date day = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
        return df.format(day);
    }

    //获取系统当前年月日(xxxx-xx-xx)
    public static String getNowDate2() {
        Date day = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return df.format(day);
    }

    //获取系统当前年月日时分秒(xxxx-xx-xx HH:mm:ss)
    public static String getNowDate3() {
        Date day = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(day);
    }

    //获取系统当前年月日(xxxx年xx月xx日)
    public static String getNowDate4() {
        Date day = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
        return df.format(day);
    }

    //处理时间戳(转换为xxxx年xx月xx日)
    public static String processDate(Timestamp time) {
        String result = "";
        if (time != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
            result = sdf.format(time);
        }
        return result;
    }

    //处理时间戳(转换为xxxx-xx-xx HH:mm:ss)
    public static String TimestampToTime(Timestamp time) {
        String result = "";
        if (time != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            result = sdf.format(time);
        }
        return result;
    }
    //处理时间戳(转换为xxxx-xx-xx HH:mm:ss)
    public static String TimestampToTimeSimple(Timestamp time) {
        String result = "";
        if (time != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            result = sdf.format(time);
        }
        return result;
    }

    //处理时间格式(字符串xxxx/xx/xx或xxxx-xx-xx或xxxx年xx月xx日转Date)
    public static Date processStrToDate(String time) {
        if (time != null) {
            time = time.replace("年", "-").replace("月", "-").replace("日", "");
            time = time.replace("/", "-");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = sdf.parse(time);
        } catch (ParseException e) {
            System.out.println("转换失败!");
        } finally {
            return date;
        }
    }

    //处理时间格式(字符串xxxx/xx/xx或xxxx年xx月xx日转xxxx-xx-xx)
    public static String processStrToStr(String time) {
        if (time != null) {
            time = time.replace("年", "-").replace("月", "-").replace("日", "");
            time = time.replace("/", "-");
        } else {
            time = "";
        }
        return time;
    }

    //处理时间格式(xxxx-xx-xx或xxxx/xx/xx → yyyy年MM月dd日)
    public static String strProcessDate(String time) {
        String result = "";
        if (time != null) {
            time = time.replace("/", "-");
        } else {
            time = "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date;
        try {
            date = sdf.parse(time);
            Timestamp timestamp = new Timestamp(date.getTime());
            result = DateUtils.processDate(timestamp);
        } catch (Exception e) {
            System.out.println("转换失败!");
            result = time;
        } finally {
            return result;
        }
    }

    //获取某一天的下一天
    public static String getNextDay(String nowDate) {
        nowDate = processStrToStr(nowDate);
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            calendar.setTime(sdf.parse(nowDate));
        } catch (ParseException e) {
            System.out.println("获取失败!");
        }
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        Date date = calendar.getTime();
        return sdf.format(date);
    }

    //获取某一天的前一天
    public static String getLastDay(String nowDate) {
        nowDate = processStrToStr(nowDate);
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            calendar.setTime(sdf.parse(nowDate));
        } catch (ParseException e) {
            System.out.println("获取失败!");
        }
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        Date date = calendar.getTime();
        return sdf.format(date);
    }

    //返回两个日期(格式可以为:xxxx/xx/xx或xxxx年xx月xx日或xxxx-xx-xx)之间的所有月份
    public static List<String> getMonthBetween(String minDate, String maxDate) {
        minDate = processStrToStr(minDate);
        maxDate = processStrToStr(maxDate);

        ArrayList<String> result = new ArrayList<String>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月

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

        Boolean flag = true;

        Date dateMin = null;
        Date dateMax = null;

        try {
            dateMin = sdf.parse(minDate);
        } catch (ParseException e) {
            System.out.println("获取失败!");
            flag = false;
        } finally {
            try {
                dateMax = sdf.parse(maxDate);
            } catch (ParseException e) {
                System.out.println("获取失败!");
                flag = false;
            } finally {
                if (flag == true) {
                    min.setTime(dateMin);
                    min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

                    max.setTime(dateMax);
                    max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

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

    //返回指定日期的当月最后一天
    public static Date getLastMonthOfDate(Date date) {
        Calendar para = Calendar.getInstance(java.util.Locale.CHINA);
        para.setTime(date);
        para.set(Calendar.DATE, para.getActualMaximum(Calendar.DAY_OF_MONTH));
        para.set(Calendar.HOUR_OF_DAY, 23);
        para.set(Calendar.MINUTE, 59);
        para.set(Calendar.SECOND, 59);
        return para.getTime();
    }

    // 将年月翻译成中文 --by liuzhidong
    private static final String[] cnChars = new String[]{"〇", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"};

    public static String getMonthInCN(int month) {
        return cnChars[month];
    }

    public static String getYearInCN(int year) {
        int[] yearInInt = new int[4];
        // 千位
        yearInInt[0] = year / 1000;
        // 百位
        yearInInt[1] = (year % 1000) / 100;
        // 十位
        yearInInt[2] = (year % 100) / 10;
        // 个位
        yearInInt[3] = year % 10;
        // 翻译
        StringBuilder result = new StringBuilder();
        for (int i1 : yearInInt) {
            result.append(cnChars[i1]);
        }
        return result.toString();
    }

    /**
     * 获取传来时间的年份和下一月份  by 张则政
     * @param yearAndMonth 年月
     * @return 年份和下月份的int数组
     */
    public static int[] yearAndMonthValue(Timestamp yearAndMonth) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(yearAndMonth);
        int year = cal.get(Calendar.YEAR);//年份
        int month = cal.get(Calendar.MONTH) + 2;//下一月
        // 月份为12时,年份设为下一年,月份设为1月
        if (month > 12) {
            month = month - 12;
            year = year + 1;
        }
        int[] yearAndMonthArr = {year, month};
        return yearAndMonthArr;
    }

    /**
     * 获取当前系统时间的年份和上一月份 by 张则政
     * @return 当前系统时间的年份和上一月份的int数组
     */
    public static int[] yearAndMonthSystem() {
        String nowDate = getNowDate();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM");
        Date d = null;
        try {
            d = sdf1.parse(nowDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(d);
        int endYear = cal1.get(Calendar.YEAR);//当前系统年
        int endMonth = cal1.get(Calendar.MONTH);//当前系统月的上一月
        int[] yearAndMonth = {endYear, endMonth};
        return yearAndMonth;
    }

    /**
     * 计算两个时间相差多少个年
     * @param start
     * @param end
     * @return
     * @throws ParseException
     */
    public static int yearsBetween(String start, String end) throws ParseException {
        startDate.setTime(sdf.parse(start));
        endDate.setTime(sdf.parse(end));
        return (endDate.get(Calendar.YEAR) - startDate.get(Calendar.YEAR));
    }

    /**
     * 计算两个时间相差多少个月  sym
     * @param start <String>
     * @param end <String>
     * @return int
     * @throws ParseException
     */
    public static int monthsBetween(String start, String end) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        startDate.setTime(sdf.parse(start));
        endDate.setTime(sdf.parse(end));
        int result = yearsBetween(start, end) * 12 + endDate.get(Calendar.MONTH) - startDate.get(Calendar.MONTH);
        return result == 0 ? 1 : Math.abs(result);
    }

    /**
     * 计算两个时间相差分钟数  sym
     * @param start 开始时间
     * @param end 结束时间
     * @return
     */
    public static int minutesBetween(String start, String end) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long minutes = 0;
        try {
            Date startDate = df.parse(start);
            Date endDate = df.parse(end);
            long diff = endDate.getTime() - startDate.getTime();// 这样得到的差值是微秒级别
            minutes = diff / (1000 * 60);
        } catch (ParseException e) {
            System.out.println("抱歉,时间日期解析出错。");
        }
        return (int)minutes;
    }
}

 类似资料: