Java 获取时间、时间处理常用方法


public class TimeCalculateUtil {

    private static SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
    private static SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM");
    private static SimpleDateFormat sdf4 = new SimpleDateFormat("yyyy");
    private static SimpleDateFormat sdf5 = new SimpleDateFormat("MM");
    private static SimpleDateFormat sdf6 = new SimpleDateFormat("dd");
    private static SimpleDateFormat sdf7 = new SimpleDateFormat("HH:mm:ss");

    public static void main(String[] args) throws ParseException {
        String stStr = "2022-08-02 00:00:00";
        String edStr = "2022-08-01 17:59:59";
//        Long stTime = TimeCutUtil.dateToStamp(beginStr);
//        DateUtil.getDays(new Date(stTime).getYear(), new Date(stTime).getMonth());
        Date stDate = sdf1.parse(stStr);
        Date edDate = sdf1.parse(edStr);

        System.out.println(stDate.getTime());
        System.out.println(edDate);
        int i = differentDays(stDate, edDate);

        System.out.println(i);
    }

    /**
     * 日期转格式化字符串
     *
     * @param type 格式化类型:1=yyyy-MM-dd HH:mm:ss,2=yyyy-MM-dd,3=yyyy-MM,
     *             4=yyyy,5=MM,6=dd,7=HH:mm:ss
     * @param date 格式化时间
     */
    public static String dateToFormatString(int type, Date date){
        String r = null;
        switch (type){
            case 1:
                r = sdf1.format(date);
                break;
            case 2:
                r = sdf2.format(date);
                break;
            case 3:
                r = sdf3.format(date);
                break;
            case 4:
                r = sdf4.format(date);
                break;
            case 5:
                r = sdf5.format(date);
                break;
            case 6:
                r = sdf6.format(date);
                break;
            case 7:
                r = sdf7.format(date);
                break;
        }
        return r;
    }

    /**
     * 字符串转格式化日期
     *
     * @param type 格式化类型:1=yyyy-MM-dd HH:mm:ss,2=yyyy-MM-dd,3=yyyy-MM,
     *             4=yyyy,5=MM,6=dd,7=HH:mm:ss
     * @param date 格式化时间
     */
    public static Date stringToFormatDate(int type, String date){
        Date r = null;
        try {
            switch (type) {
                case 1:
                    r = sdf1.parse(date);
                    break;
                case 2:
                    r = sdf2.parse(date);
                    break;
                case 3:
                    r = sdf3.parse(date);
                    break;
                case 4:
                    r = sdf4.parse(date);
                    break;
                case 5:
                    r = sdf5.parse(date);
                    break;
                case 6:
                    r = sdf6.parse(date);
                    break;
                case 7:
                    r = sdf7.parse(date);
                    break;
            }
        } catch (Exception ex){
            ex.printStackTrace();
            return null;
        }
        return r;
    }

    /**
     * 获取某年某月的最后一天 如201712结果为2017-12-30
     * @param year 年
     * @param month 月
     * @return
     */
    public  static String getLastDay(String year,String month){
        LocalDate firstDayOfCurrentDate = LocalDate.of(Integer.parseInt(year), Integer.parseInt(month), 1);
        LocalDate lastDayOfCurrentDate = firstDayOfCurrentDate.with(TemporalAdjusters.lastDayOfMonth());
        return lastDayOfCurrentDate.toString();
    }

    /**
     * 计算当前月有多少天
     *
     * @param year  年
     * @param month 月
     * @return 天数
     */
    public static int getDays(int year, int month) {
        int days = 0;
        if (month != 2) {
            switch (month) {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    days = 31;
                    break;
                case 4:
                case 6:
                case 9:
                case 11:
                    days = 30;

            }
        } else {
            // 闰年
            if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
                days = 29;
            else
                days = 28;
        }
        System.out.println("当月有" + days + "天!");
        return days;
    }

    /**
     * edDate比stDate多的天数
     *
     * @param stDate 开始时间
     * @param edDate 结束时间
     * @return
     */
    public static int differentDays(Date stDate, Date edDate) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(stDate);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(edDate);
        int day1 = cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if (year1 != year2) {//同一年
            int timeDistance = 0;
            for (int i = year1; i < year2; i++) {
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0)    //闰年
                {
                    timeDistance += 366;
                } else    //不是闰年
                {
                    timeDistance += 365;
                }
            }

            return timeDistance + (day2 - day1);
        } else {// 不同年
            System.out.println("判断day2 - day1 : " + (day2 - day1));
            return day2 - day1;
        }
    }

    /**
     * edDate比stDate多的几分钟
     *
     * @param stDate 开始时间
     * @param edDate 结束时间
     * @return
     */
    public static int differentMinutes(Date stDate, Date edDate) {
        long millis = edDate.getTime() - stDate.getTime();
        long minutes = millis / 1000 / 60;
        return (int) minutes;
    }

    /**
     * edDate比stDate多的几分钟
     *
     * @param stDate 开始时间
     * @param edDate 结束时间
     * @return
     */
    public static Double differentHours(Date stDate, Date edDate) {
        long millis = edDate.getTime() - stDate.getTime();
        Double hours = new BigDecimal(millis / 1000 / 60 / 60D).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
        return hours;
    }

    /**
     * 判断当前日期是星期几
     *
     * @param pTime 修要判断的时间
     * @return dayForWeek 判断结果
     * @Exception 发生异常
     */
    public static int dayForWeek(String pTime) {
        int dayForWeek = 0;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        try {
            c.setTime(format.parse(pTime));
            if (c.get(Calendar.DAY_OF_WEEK) == 1) {
                dayForWeek = 7;
            } else {
                dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dayForWeek;
    }

    /**
     * @param dt
     * @return 当前日期是星期几
     */

    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};

        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);

        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;

        return weekDays[w];
    }

    /**
     * 根据日期获得星期
     *
     * @param date
     * @return
     */
    public static String getWeekOfDate(String date) {
        if (StringUtils.isEmpty(date)) {
            return "";
        }

        String[] weekDaysName = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date dt1;

        try {
            dt1 = df.parse(date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dt1);
            int intWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
            return weekDaysName[intWeek];
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取当前时间为第几周
     * @param date
     * @return
     */
    public static int getWeekDate(Date date){
        int weekOfYear;
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.setFirstDayOfWeek(Calendar.MONDAY);
            calendar.setTime(date);
            weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
        }catch(Exception e) {
            e.printStackTrace();
            return  0;
        }
        return weekOfYear;
    }

    /**
     * 计算两个时间相差几个月
     * @param start
     * @param end
     * @return
     */
    public static int getDifferentMonths(Date start, Date end) {
        if (start.after(end)) {
            Date t = start;
            start = end;
            end = t;
        }
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTime(start);
        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTime(end);
        Calendar temp = Calendar.getInstance();
        temp.setTime(end);
        temp.add(Calendar.DATE, 1);
        int year = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
        int month = endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);
        if ((startCalendar.get(Calendar.DATE) == 1)&& (temp.get(Calendar.DATE) == 1)) {
            return year * 12 + month + 1;
        } else if ((startCalendar.get(Calendar.DATE) != 1) && (temp.get(Calendar.DATE) == 1)) {
            return year * 12 + month;
        } else if ((startCalendar.get(Calendar.DATE) == 1) && (temp.get(Calendar.DATE) != 1)) {
            return year * 12 + month;
        } else {
            return (year * 12 + month - 1) < 0 ? 0 : (year * 12 + month);
        }
    }

    /**
     * 获取当前时间的前后月
     *
     * @param date 时间
     * @param type 类型:1=天,2=月,3=年
     * @param val 前后时间值
     * @return
     */
    public static Date getNowAroundTime(Date date,String type,int val) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        switch (type){
            case "1":
                calendar.add(calendar.DATE, val); //设置为前几天
                break;
            case "2":
                calendar.add(calendar.MONTH, val); //设置为前几月
                break;
            case "3":
                calendar.add(calendar.YEAR, val); //设置为前几年
                break;
        }
        Date date1 = calendar.getTime();
        //String defaultStartDate = sdf1.format(date1); //格式化前month月的时间
        return date1;
    }

    /**
     * 获取当前时间一周开始时间和结束时间
     * @return
     */
    public static long[] getCurrentWeekTimeFrame() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        //start of the week
        if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            calendar.add(Calendar.DAY_OF_YEAR,-1);
        }
        calendar.add(Calendar.DAY_OF_WEEK, -(calendar.get(Calendar.DAY_OF_WEEK) - 2));
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        long startTime = calendar.getTimeInMillis();
        //end of the week
        calendar.add(Calendar.DAY_OF_WEEK, 6);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        long endTime = calendar.getTimeInMillis();
        return new long[]{startTime, endTime};
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值