Java关于处理年月日,时间的方法

    /**
     * 当天的最大值
     *
     * @param date
     * @param isMax 0=00:00:00;  1=23:59:59
     * @return
     */
    public static Date getDate(Date date, int isMax) {
        Calendar c = Calendar.getInstance();
        if (null != date) {
            c.setTime(date);
        }
        if (0 == isMax) {
            c.set(Calendar.HOUR_OF_DAY, 00);
            c.set(Calendar.MINUTE, 00);
            c.set(Calendar.SECOND, 00);
        } else {
            c.set(Calendar.HOUR_OF_DAY, 23);
            c.set(Calendar.MINUTE, 59);
            c.set(Calendar.SECOND, 59);
        }
        return c.getTime();
    }

    /**
     * 获取当前年
     *
     * @return
     */
    public static int getYear(Date date) {
        if (null == date) {
            date = now();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c.get(Calendar.YEAR);
    }

    /**
     * 获取月
     *
     * @return
     */
    public static int getMonth(Date date) {
        if (null == date) {
            date = now();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c.get(Calendar.MONTH) + 1;
    }

    /**
     * 获取日
     *
     * @return
     */
    public static int getDay(Date date) {
        if (null == date) {
            date = now();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 获取总毫秒数
     *
     * @return
     */
    public static long nowTimeMillis() {
        return System.currentTimeMillis();
    }


    /**
     * 获取当前时间
     *
     * @return
     */
    public static Date now() {
        return new Date();
    }

    /**
     * 字符串时间装换为日期,如:2009-11-11 11:11:11,如果没有秒,根据后边参数,如果是1则添加23:59:59
     *
     * @param time
     */
    public static Date getTime(String time, int isMax) {

        try {
            time = time.trim();
            if (time.indexOf(" ") <= 0) {
                if (isMax == 0) {
                    time += " 00:00:00";
                } else {
                    time += " 23:59:59";
                }
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.parse(time);
        } catch (Exception ex) {
        }
        return null;
    }

    /**
     * 字符串时间装换为日期,如:2009-11-11 11:11:11
     *
     * @param time
     */
    public static Date getTime(String time) {
        if (null == time) {
            return now();
        }
        try {
            time = time.trim();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.parse(time);
        } catch (Exception ex) {
        }
        return null;
    }

    /**
     * 字符串时间装换为日期,如:2009-11-11 11:11:11
     *
     * @param time
     */
    public static Date getTime(String time, String formatStr) {
        if (null == time) {
            return now();
        }
        try {
            time = time.trim();
            SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
            return sdf.parse(time);
        } catch (Exception ex) {
        }
        return null;
    }


    /**
     * 格式化日期
     *
     * @param date
     * @param formatStr yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String getTimeStr4Format(Date date,
                                           String formatStr) {
        if (null == date) {
            date = now();
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
            return sdf.format(date);
        } catch (Exception ex) {
        }
        return null;
    }



    /**
     * 转换为日期时间字符串
     *
     * @param date
     * @return
     */
    public static String getTimeStr(Date date) {
        if (null == date) {
            date = now();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

    /**
     * 转换为日期字符串 yyyy-MM-dd
     *
     * @param date
     * @return
     */
    public static String getYYYMMDD(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (null == date) {
            return sdf.format(now());
        }
        return sdf.format(date);
    }

    /**
     * 周的第一天
     *
     * @param date
     * @return
     */
    public static Date getWeekFirstDay(Date date) {
        if (null == date) {
            date = now();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.DAY_OF_WEEK, c.getActualMinimum(Calendar.DAY_OF_WEEK));
        c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) + 1);
        c.set(Calendar.HOUR_OF_DAY, 00);
        c.set(Calendar.MINUTE, 00);
        c.set(Calendar.SECOND, 00);
        return c.getTime();
    }

    /**
     * 周的最后一天
     *
     * @param date
     * @return
     */
    public static Date getWeekLastDay(Date date) {
        if (null == date) {
            date = now();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.DAY_OF_WEEK, c.getActualMaximum(Calendar.DAY_OF_WEEK));
        c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) + 1);
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.MINUTE, 59);
        c.set(Calendar.SECOND, 59);
        return c.getTime();
    }

    /**
     * 月的第一天
     *
     * @param date
     * @return
     */
    public static Date getMonthFirstDay(Date date) {
        if (null == date) {
            date = now();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.DAY_OF_MONTH, c.getActualMinimum(Calendar.DAY_OF_MONTH));
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        return c.getTime();
    }

    /**
     * 月的最后一天
     *
     * @param date
     * @return
     */
    public static Date getMonthLastDay(Date date) {
        if (null == date) {
            date = now();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.MINUTE, 59);
        c.set(Calendar.SECOND, 59);
        return c.getTime();
    }

    /**
     * 年的第一天
     *
     * @param date
     * @return
     */
    public static Date getYearFirstDay(Date date) {
        if (null == date) {
            date = now();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.DAY_OF_YEAR, c.getActualMinimum(Calendar.DAY_OF_YEAR));
        c.set(Calendar.HOUR_OF_DAY, 00);
        c.set(Calendar.MINUTE, 00);
        c.set(Calendar.SECOND, 00);
        return c.getTime();
    }

    /**
     * 年的最后一天
     *
     * @param date
     * @return
     */
    public static Date getYearLastDay(Date date) {
        if (null == date) {
            date = now();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.DAY_OF_YEAR, c.getActualMaximum(Calendar.DAY_OF_YEAR));
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.MINUTE, 59);
        c.set(Calendar.SECOND, 59);
        return c.getTime();
    }


    
    /**
     * 日期添加秒数
     *
     * @return
     */
    public static Date addSec(Date date, int sec) {
        if (null == date) {
            date = now();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.SECOND, c.get(Calendar.SECOND) + sec);
        return c.getTime();
    }

    /**
     * 日期添加分钟数
     *
     * @return
     */
    public static Date addMin(Date date, int min) {
        if (null == date) {
            date = now();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.MINUTE, c.get(Calendar.MINUTE) + min);
        return c.getTime();
    }

    /**
     * 得到几天前的时间
     *
     * @param lastDay
     * @return
     */
    public static Date getLastDay(int lastDay) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) - lastDay);
        c.set(Calendar.SECOND, 00);
        c.set(Calendar.HOUR_OF_DAY, 00);
        c.set(Calendar.MINUTE, 00);
        return c.getTime();
    }

    /**
     * 得到几天前的时间
     *
     * @param lastDay
     * @param isMax   0=00:00:00,1=23:59:59
     * @return
     */
    public static Date getLastDay(Date date, int lastDay, int isMax) {
        Calendar c = Calendar.getInstance();
        if (null != date) {
            c.setTime(date);
        }
        c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) - lastDay);
        if (0 == isMax) {
            c.set(Calendar.HOUR_OF_DAY, 00);
            c.set(Calendar.MINUTE, 00);
            c.set(Calendar.SECOND, 00);
        } else {
            c.set(Calendar.HOUR_OF_DAY, 23);
            c.set(Calendar.MINUTE, 59);
            c.set(Calendar.SECOND, 59);
        }
        return c.getTime();
    }

    /**
     * 得到前几个月
     *
     * @param lastMonth
     * @return
     */
    public static Date getLastMonth(Date date, int lastMonth) {
        Calendar c = Calendar.getInstance();
        if (null != date) {
            c.setTime(date);
        }
        c.set(Calendar.MONTH, c.get(Calendar.MONTH) - lastMonth);
        c.set(Calendar.SECOND, 00);
        c.set(Calendar.HOUR_OF_DAY, 00);
        c.set(Calendar.MINUTE, 00);
        return c.getTime();
    }

    /**
     * 得到后几个月
     *
     * @param date
     * @param lastMonth
     * @return
     */
    public static Date getAfterMonth(Date date, int lastMonth) {
        Calendar c = Calendar.getInstance();
        if (null != date) {
            c.setTime(date);
        }
        c.set(Calendar.MONTH, c.get(Calendar.MONTH) + lastMonth);
        c.set(Calendar.SECOND, 00);
        c.set(Calendar.HOUR_OF_DAY, 00);
        c.set(Calendar.MINUTE, 00);
        return c.getTime();
    }

    /**
     * 取时间段之间的日期
     * 例如:取2008-12 到2009-01 之间的日期,即2008-12,2009-01
     *
     * @param d1
     * @param d2
     * @return
     * @throws ParseException
     */
    public static GregorianCalendar[] getDate(String d1, String d2)
            throws ParseException {
        Vector<GregorianCalendar> v = new Vector<GregorianCalendar>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        GregorianCalendar gc1 = new GregorianCalendar(), gc2 = new GregorianCalendar();
        gc1.setTime(sdf.parse(d1));
        gc2.setTime(sdf.parse(d2));
        do {
            GregorianCalendar gc3 = (GregorianCalendar) gc1.clone();
            v.add(gc3);
            gc1.add(Calendar.MONTH, 1);
        } while (!gc1.after(gc2));
        return v.toArray(new GregorianCalendar[v.size()]);
    }

    /**
     * 获取年月日之间的数组
     *
     * @param sd
     * @param ed
     * @return
     * @throws ParseException
     */
    public static List<String> getYYYYMMs(String sd, String ed) throws ParseException {
        List<String> list = new ArrayList<String>();
        GregorianCalendar[] ga = getDate(sd, ed);
        for (GregorianCalendar e : ga) {
            int year = e.get(Calendar.YEAR);
            int month = e.get(Calendar.MONTH) + 1;
            if (month < 10) {
                list.add(year + "0" + month);
            } else {
                list.add(year + "" + month);
            }
        }
        return list;
    }

    /**
     * 获取两个日期之间的差,to-from
     *
     * @param from
     * @param to
     * @return
     */
    public static int getDaysBetween(Date from, Date to) {
        long toLong = to.getTime();
        long fromLong = from.getTime();
        String between_days = String.valueOf((toLong - fromLong) / (1000 * 60 * 60 * 24));
        return Integer.parseInt(between_days);
    }

    /**
     * 获取月列表
     *
     * @param addMonth
     * @return
     */
    public static List<String> getYYYYMMs(int addMonth) {
        List<String> list = new ArrayList<>();
        int count = Math.abs(addMonth);
        for (int i = 0; i < count; i++) {
            Calendar c = Calendar.getInstance();
            if (addMonth > 0) {
                c.set(Calendar.MONTH, c.get(Calendar.MONTH) + i);
            } else {
                c.set(Calendar.MONTH, c.get(Calendar.MONTH) - i);
            }
            list.add(getTimeStr4Format(c.getTime(), "yyyyMM"));
        }
        return list;
    }

    /**
     * 获取日
     *
     * @param flag 时间0返回00:00:00,1返回23:59:59
     * @return
     */
    public static Date getNowDay(int flag) {
        if (0 == flag) {
            return getTime(getYYYMMDD(now()) + " 00:00:00");
        } else {
            return getTime(getYYYMMDD(now()) + " 23:59:59");
        }
    }

    /**
     * 判断日期是否在两个日期之间
     *
     * @param date
     * @param startTime
     * @param endTime
     * @return
     */
    public static boolean isBetween(Date date, Date startTime, Date endTime) {
        if (null == date) {
            date = now();
        }
        if (date.after(startTime) && date.before(endTime)) {
            return true;
        }
        return false;
    }

    /**
     * 获取开始时间
     *
     * @param type 0月,1季度,2半年,3年度
     * @param date
     * @return
     */
    public static Date getStartDate(int type, Date date) {
        if (null == date) {
            date = now();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int currentMonth = c.get(Calendar.MONTH) + 1;
        switch (type) {
            case 0:
                return getMonthFirstDay(date);
            case 1:
                if (currentMonth >= 1 && currentMonth <= 3) {
                    c.set(Calendar.MONTH, 0);
                } else if (currentMonth >= 4 && currentMonth <= 6) {
                    c.set(Calendar.MONTH, 3);
                } else if (currentMonth >= 7 && currentMonth <= 9) {
                    c.set(Calendar.MONTH, 4);
                } else if (currentMonth >= 10 && currentMonth <= 12) {
                    c.set(Calendar.MONTH, 9);
                }
                c.set(Calendar.DAY_OF_MONTH, 1);
                return getMonthFirstDay(c.getTime());
            case 2:
                if (currentMonth > 6) {
                    c.set(Calendar.MONTH, 6);
                } else {
                    c.set(Calendar.MONTH, 0);
                }
                return getMonthFirstDay(c.getTime());
            case 3:
                return getYearFirstDay(c.getTime());
            default:
                return null;
        }
    }

    /**
     * 获取结束时间
     *
     * @param type 0月,1季度,2半年,3年度
     * @param date
     * @return
     */
    public static Date getEndDate(int type, Date date) {
        if (null == date) {
            date = now();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int currentMonth = c.get(Calendar.MONTH) + 1;
        switch (type) {
            case 0:
                return getMonthLastDay(date);
            case 1:
                try {
                    if (currentMonth >= 1 && currentMonth <= 3) {
                        c.set(Calendar.MONTH, 2);
                    } else if (currentMonth >= 4 && currentMonth <= 6) {
                        c.set(Calendar.MONTH, 5);
                    } else if (currentMonth >= 7 && currentMonth <= 9) {
                        c.set(Calendar.MONTH, 8);
                    } else if (currentMonth >= 10 && currentMonth <= 12) {
                        c.set(Calendar.MONTH, 11);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return getMonthLastDay(c.getTime());
            case 2:
                if (currentMonth > 6) {
                    c.set(Calendar.MONTH, 11);
                } else {
                    c.set(Calendar.MONTH, 5);
                }
                return getMonthLastDay(c.getTime());
            case 3:
                return getYearLastDay(c.getTime());
            default:
                return null;
        }
    }

    /**
     * 得到前后几年
     *
     * @param last  前几年
     * @param after 后几年
     * @return
     */
    public static List<Integer> getYearList(int last, int after) {
        int year = getYear(now());
        List<Integer> list = new ArrayList<>();
        for (int i = year - last; i <= year + after; i++) {
            list.add(i);
        }
        return list;
    }

    /**
     * 获取前几天的列表
     *
     * @param addDay
     * @return
     */
    public static List<Date> getDayList(int addDay) {
        List<Date> list = new ArrayList<>();
        int count = Math.abs(addDay);
        for (int i = 0; i < count; i++) {
            Calendar c = Calendar.getInstance();
            if (addDay > 0) {
                c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) + i);
            } else {
                c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) - i);
            }
            list.add(c.getTime());
        }
        return list;
    }

    /**
     * 获取前几月的列表
     *
     * @param addMonth
     * @return
     */
    public static List<Date> getMonthList(int addMonth) {
        List<Date> list = new ArrayList<>();
        int count = Math.abs(addMonth);
        for (int i = 0; i < count; i++) {
            Calendar c = Calendar.getInstance();
            if (addMonth > 0) {
                c.set(Calendar.MONTH, c.get(Calendar.MONTH) + i);
            } else {
                c.set(Calendar.MONTH, c.get(Calendar.MONTH) - i);
            }
            list.add(c.getTime());
        }
        return list;
    }

    /**
     * 获取天数集合
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<Date> getDayList(Date startTime, Date endTime) {
        if (null == startTime) {
            return null;
        }
        if (null == endTime) {
            endTime = now();
        }
        List<Date> list = new ArrayList<>();
        int count = getDaysBetween(startTime, endTime);
        for (int i = 0; i <= count; i++) {
            list.add(getLastDay(startTime, -1 * i, 0));
        }
        return list;
    }
    
    /**
     * 获取天数集合
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<Date> getMonthList(Date startTime, Date endTime) {
        if (null == startTime) {
            return null;
        }
        if (null == endTime) {
            endTime = now();
        }
        List<Date> list = new ArrayList<>();
        List<String> monthList = new ArrayList<>();
        try {
            monthList = getYYYYMMs(getTimeStr4Format(startTime, "yyyy-MM"), getTimeStr4Format(endTime, "yyyy-MM"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        for (String string : monthList) {
            list.add(getTime(string, "yyyyMM"));
        }
        return list;
    }

    /**
     * 时间戳转换成日期格式字符串
     *
     * @param seconds 精确到秒的字符串
     * @param format
     * @return
     */
    public static String timeStamp2Date(String seconds, String format) {
        if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
            return "";
        }
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds + "000")));
    }

    /**
     * 根据秒转换成时分秒格式
     *
     * @param second
     */
    public static String formatSecond(long second) {
        DecimalFormat df = new DecimalFormat("#00");
        long hours = second / 3600;//转换小时数
        second = second % 3600;//剩余秒数
        long minutes = second / 60;//转换分钟
        second = second % 60;//剩余秒数
        return df.format(hours) + ":" + df.format(minutes) + ":" + df.format(second);
    }

    public static String qianDate(int num) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.add(calendar.HOUR_OF_DAY, num);
        return sdf.format(calendar.getTime());
    }

    /**
     * 统计两个时间的时间差
     * 相差几秒几毫秒
     */
    public static String getDistanceTime(String str1, String str2) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date one;
        Date two;
        long day = 0;//天数差
        long hour = 0;//小时数差
        long min = 0;//分钟数差
        long second = 0;//秒数差
        long diff = 0;//毫秒差
        String result = null;
        try {
            final Calendar c = Calendar.getInstance();
            c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
            one = df.parse(str1);
            c.setTime(one);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            diff = time2 - time1;
            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            second = diff / 1000;
//			System.out.println("day="+day+" hour="+hour+" min="+min+" ss="+second%60);

            if (day > 0) {
                result = day + "天" + hour + "小时" + min + "分" + second % 60 + "秒";
            } else if (hour > 0) {
                result = hour + "小时" + min + "分" + second % 60 + "秒";
            } else if (min > 0) {
                result = min + "分" + second % 60 + "秒";
            } else {
                result = second % 60 + "秒";
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值