一些时间相关的结算,包含年龄计算,时间,日期的一些方法

日常用的一些小方法,记录一下


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * 杨·人间雕塑·下凡的天使·行走的大卫·拥有盛世美颜且智勇双全的芳心纵火犯·福尔摩帅·十亿少女的梦·猛的自用方法
 */
public class ym {
   /**
     * java8的去重查询方法,但是此方法不能传空值,会报错
     * @param keyExtractor
     * @param <T>
     * @return 返回去重后的值
     */
    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Set<Object> seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(keyExtractor.apply(t));
    }

    /**
     * 返回现在时间的方法
     * @return time 表示现在时间
     */
    public static String nowTime(){
        Date day=new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(day);
        return time;
    }

	/**
     * 将long类型的时间戳转化为  时分秒.毫秒  格式 
     * @return date 表示时间
     */
    public String getStandardTime(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS",
                Locale.getDefault());
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+0"));
        Date date = new Date(timestamp + 0 * 60 * 60 * 1000);
        sdf.format(date);
        return sdf.format(date);
    }

   /**
     * 获得当天零时零分零秒
     * @return
     */
    public static String nowDayOfZero() {
        Date day=new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        String time = df.format(day);
        return time;
    }
	
    /**
     * 获得当天23:59:59
     * @return
     */
    public static String nowDayOfLast() {
        Date day=new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
        String time = df.format(day);
        return time;
    }

    /**
     * 获得前一天零时零分零秒
     * @return
     */
    public static String yesterdayOfZero() {
        //获取当前年月日的前一天 并转换成字符串
        //当前日期
        Calendar calendar = Calendar.getInstance();
        Date date = new Date();
        calendar.setTime(date);
        //calendar.add方法获取前一天日期
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        date = calendar.getTime();

        //格式转换
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        String s = sdf.format(date);
        return s;
    }

    /**
     * 获得前一天23:59:59
     * @return
     */
    public static String yesterdayOfLast() {
        //获取当前年月日的前一天 并转换成字符串
        //当前日期
        Calendar calendar = Calendar.getInstance();
        Date date = new Date();
        calendar.setTime(date);
        //calendar.add方法获取前一天日期
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        date = calendar.getTime();

        //格式转换
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
        String s = sdf.format(date);
        return s;
    }


    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date day=new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String time = df.format(day);
        return time;
    }


    /**
     * 查询一段时间内的数据,比如近一周,近一月,近一天
     * @param X 查询多少天内的数据就传数字几
     * @return 日期
     */
    public static String time(int X){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DATE, - X);
        Date d = c.getTime();
        String day = format.format(d);
        return day;
    }
	
    /**
     * Description://根据字符日期返回星期几
     * 
     */
    public static String getWeek(String dateTime){
        String week = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = sdf.parse(dateTime);
            SimpleDateFormat dateFm = new SimpleDateFormat("EEEE");
            week = dateFm.format(date);
            week=week.replaceAll("星期","周");
        }catch (ParseException e){
            //LogerUtil.log(ym.class, "getWeek", e);
        }
        return week;
    }

    /**
     * 获取过去7天内的日期数组
     * @param intervals      intervals天内
     * @return              日期数组
     */
    public static ArrayList<String> getDays(int intervals) {
        ArrayList<String> pastDaysList = new ArrayList<>();
        for (int i = intervals -1; i >= 0; i--) {
            pastDaysList.add(getPastDate(i));
        }
        return pastDaysList;
    }
	
    /**
     * 获取过去第几天的日期
     * @param past
     * @return
     */
    public static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }

	/**
     * 计算相差天数
     *
     * @param a 开始时间
     * @param b 结束时间
     * @return
     */
    public static Long between_days(String a, String b) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// 自定义时间格式
        Calendar calendar_a = Calendar.getInstance();// 获取日历对象
        Calendar calendar_b = Calendar.getInstance();

        Date date_a = null;
        Date date_b = null;

        try {
            date_a = simpleDateFormat.parse(a);//字符串转Date
            date_b = simpleDateFormat.parse(b);
            calendar_a.setTime(date_a);// 设置日历
            calendar_b.setTime(date_b);
        } catch (ParseException e) {
            e.printStackTrace();//格式化异常
        }
        long time_a = calendar_a.getTimeInMillis();
        long time_b = calendar_b.getTimeInMillis();
        long between_days = (time_b - time_a) / (1000 * 3600 * 24);//计算相差天数

        return between_days;
    }

	/**
	*
	*获取两个时间点之间的日期list
	*
	*/
    public List<String> dateList(String startTime, String endTime) {
        List<String> list = new ArrayList<>();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date start = dateFormat.parse(startTime);
            Date end = dateFormat.parse(endTime);
            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);

            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.DATE, +1);
            while (tempStart.before(tempEnd)) {
                list.add(dateFormat.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 获取本周的日期(周一至周日)
     * @return
     */
    public static List<String> getTimeInterval() {
        List<String> l = new ArrayList<String>();
        Date date = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        // 判断要计算的日期是否是周日,如果是则减一天计算周六的,否则会出问题,计算到下一周去了
        int dayWeek = c.get(Calendar.DAY_OF_WEEK);    // 获得当前日期是一个星期的第几天 (周日~周一)
        if (1 == dayWeek) {
            c.add(Calendar.DAY_OF_MONTH, -1);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //设置一周第一天为周一
        c.setFirstDayOfWeek(Calendar.MONDAY);

        int day= c.get(Calendar.DAY_OF_WEEK);    // 获得当前日期是一个星期的第几天  (周一~周日)

        int firstDayOfWeek = c.getFirstDayOfWeek();        // 2
        // 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
        c.add(Calendar.DATE, firstDayOfWeek - day);
        String imptimeBegin = sdf.format(c.getTime());
        //System.err.println("所在周星期一的日期:" + imptimeBegin);
        Date time = c.getTime();
        l.add(imptimeBegin);
        for (int i = 1; i < 7; i++) {
            date = new Date(time.getTime());    //获得周一日期时间
            c = Calendar.getInstance();
            c.setTime(date);
            c.add(Calendar.DATE, i);
            String imptimeEnd = sdf.format(c.getTime());
            l.add(imptimeEnd);
        }
        return l;
    }

    /**
     * 获取上周的日期(周一至周日)
     * @return
     */
    public static List<String> getLastTimeInterval(){
        Calendar c = Calendar.getInstance();
        int dayWeek = c.get(Calendar.DAY_OF_WEEK)-1;    //获取今天是本周的第几天
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<String> l = new ArrayList<String>();
        String lastDate;
        if (0==dayWeek) {        //正好是周日
            for (int i = -6; i <= 0; i++) {
                c = Calendar.getInstance();
                dayWeek = c.get(Calendar.DAY_OF_WEEK)-1;
                c.add(Calendar.DATE, i-7);
                lastDate = sdf.format(c.getTime());
                l.add(lastDate);
            }
        }else {
            for (int i = 1; i <= 7; i++) {
                c = Calendar.getInstance();
                dayWeek = c.get(Calendar.DAY_OF_WEEK)-1;
                int offset = i - dayWeek;
                c.add(Calendar.DATE, offset - 7);
                lastDate = sdf.format(c.getTime());
                l.add(lastDate);
            }
        }
        return l;
    }


    /**
     * 获取年龄
     * @param idCard   身份证号
     * @return
     */
    public static int age(String idCard){
        //截取身份证出生年月日
        int year = Integer.parseInt(idCard.substring(6,10));
        int month = Integer.parseInt(idCard.substring(10,12));
        int day = Integer.parseInt(idCard.substring(12,14));

        //根据日期计算年龄
        Calendar cal = Calendar.getInstance();
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH)+1;  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期

        LocalDate date1 = LocalDate.of(yearNow, monthNow, dayOfMonthNow);
        LocalDate date2 = LocalDate.of(year,month, day);
        int age = date2.until(date1).getYears();

        return age;
    }

    /**
     * 获取年龄
     * @param birth   出生日期
     * @return
     */
    public static int age_birth(String birth){
        //截取身份证出生年月日
        int year = Integer.parseInt(birth.substring(0,4));
        int month = Integer.parseInt(birth.substring(5,7));
        int day = Integer.parseInt(birth.substring(8,10));

        //根据日期计算年龄
        Calendar cal = Calendar.getInstance();
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH)+1;  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期

        LocalDate date1 = LocalDate.of(yearNow, monthNow, dayOfMonthNow);
        LocalDate date2 = LocalDate.of(year,month, day);
        int age = date2.until(date1).getYears();

        return age;
    }


    /**
     * 求指定日期加N年 ,例如:2022+10年
     * @param date 需要增加的日期字符串
     * @param oriDateFormat 需要增加的日期字符串的日期格式 例如:yyyy-MM-dd
     * @param targetDateFormat 增加N年后的日期需要什么样的格式 例如:yyyy.MM.dd
     * @param n 增加的年(天、月)数
     * @param type 年数(天数、月数)增加
     * @return 增加n年后的指定格式日期字符串
     */
    public static String dateAddYear(String date,String oriDateFormat,String targetDateFormat,int n,String type) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(oriDateFormat);

        if (StringUtils.isEmpty(date) || StringUtils.isEmpty(oriDateFormat) ||StringUtils.isEmpty(targetDateFormat)) {
            return simpleDateFormat.format(new Date());
        }


        Date dateObj = null;
        try {
            dateObj = simpleDateFormat.parse(date);
        } catch (ParseException e) {
            return simpleDateFormat.format(new Date());
        }

        Calendar cal = Calendar.getInstance();
        cal.setTime(dateObj);//设置起时间

        if (type.equals("year")){
            cal.add(Calendar.YEAR, n);//年份加法
        }
        if (type.equals("day")){
            cal.add(Calendar.DATE, n);//天数增加
        }
        //cd.add(Calendar.MONTH, 3);//增加3个月
        //cd.add(Calendar.DATE, 10);//增加10天
        //cd.add(Calendar.DATE, -20);//减20天
        SimpleDateFormat sdf = new SimpleDateFormat(targetDateFormat);
        String dateStr = sdf.format(cal.getTime());
        return dateStr;
    }



/**
     * 下面的是从若依里面拿到的时间工具类
     *	和上面的方法或许会有重复  后面有时间可整理
     * 
     */
	
	public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";
    public static String YYYYMMDD = "yyyyMMdd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }


/**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    public static Date getSpecifiedDayAfter(Date date, int afterDay) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int day = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day + afterDay);
        return c.getTime();
    }

/**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 计算当前时间是否在两个时间之内
     */
    public static boolean isDateBetweenOtherDate(Date startDate, Date endDate, Date nowDate) {
        // 获得两个时间的毫秒时间差异
        boolean start = startDate.getTime() <= nowDate.getTime();
        boolean end = endDate.getTime() >= nowDate.getTime();
        return start && end;
    }

    /**
     * 计算两个时间的差值(天)
     */
    public static int getTimeDifference(Date startDate, Date endDate) {
        // 获得两个时间的毫秒时间差异
        long day = (endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24);
        return (int) day;
    }

/**
     * 00:00:26.60 转化成毫秒
     *
     * @param strTime
     * @return
     */
    public static long getLongTime(String strTime) {
        if (StringUtils.isEmpty(strTime)) {
            return 0;
        }
        String[] ss = strTime.split("\\.");
        String[] as = ss[0].split(":");
        int sss = 0;
        if (ss.length > 1) {
            sss = (int) (Double.parseDouble("0." + ss[1]) * 1000);
        }
        long longTime = 0;
        if (as.length == 2) {
            longTime = (Integer.parseInt(as[0]) * 60 + Integer.parseInt(as[1])) * 1000 + sss;
        } else {
            longTime = (Integer.parseInt(as[0]) * 60 * 60 + Integer.parseInt(as[1]) * 60 + Integer.parseInt(as[2])) * 1000 + sss;
        }
        return longTime;
    }

    /**
     * 毫秒转化成 00:00:26
     *
     * @param time
     * @return
     */
    public static String getStringTime(long time) {
        if (time <= 0) {
            return "00:00:00";
        }
        long S = Math.round(time / 1000.0);
        long ss = S % 60;
        long mm = (S / 60) % 60;
        long hh = (S / 60 / 60) % 24;
        String h = String.valueOf(hh);
        String m = String.valueOf(mm);
        String s = String.valueOf(ss);
        String tt = (h.length()==1 ? "0"+h : h) + ":" +(m.length()==1 ? "0"+m : m) + ":" + (s.length()==1 ? "0"+s : s);
        return tt;
    }
/**
     * 00:00:26.600 转化成毫秒
     *
     * @param time
     * @return
     */
    public static String getStringTime_HHmmss_SS(long time) {
        if (time <= 0) {
            return "00:00:00.0";
        }
        long S = time % 1000;
        long ss = (time / 1000) % 60;
        long mm = (time / 1000 / 60) % 60;
        long hh = (time / 1000 / 60 / 60) % 24;
        String h = String.valueOf(hh);
        String m = String.valueOf(mm);
        String s = String.valueOf(ss);
        String tt = (h.length()==1 ? "0"+h : h) + ":" +(m.length()==1 ? "0"+m : m) + ":" + (s.length()==1 ? "0"+s : s)+ "." + S;
        return tt;
    }


    /**
     * 00:26 转化成分钟
     *
     * @param time
     * @return
     */
    public static String getStringTime_mmss_S(long time) {
        if (time <= 0) {
            return "00:00";
        }
        long S = time % 1000;
        long ss = (time / 1000) % 60;
        long mm = (time / 1000 / 60) % 60;
        long hh = (time / 1000 / 60 / 60) % 24;
        String m = String.valueOf(mm + hh * 60);
        String s = String.valueOf(ss);
        String tt = (m.length()==1 ? "0"+m : m) + ":" + (s.length()==1 ? "0"+s : s)+ "." + S;
        return tt;
    }

/**
     * ********************   计算时间的前几个小时  , 和后几个小时   **************************************************************
     */

    /**
     * 返回 String 类型 前几个小时的方法
     * time 传入的时间 例如       2021-05-28 10:06:12
     * ihour 相差的小时 例如     5
     * 前几小时写负数   -5
     * 后几小时写正数    5
     */
    public static String lastOrAfterHour(String times, int ihour) {
        String forecastTime = new String();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = simpleDateFormat.parse(times);
            calendar.setTime(date);
            calendar.add(Calendar.HOUR_OF_DAY, ihour);
            forecastTime = simpleDateFormat.format(calendar.getTime());
            return forecastTime;
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        return "";
    }

    /**
     * ********   计算时间的前几个小时  , 和后几个小时,结束   **************************************************************
     */

    /**
     * 转换时间格式  0:0:0 => 00:00:00
     *
     * @param time
     * @return
     */
    public static String formatString_HHmmss(String time) {
        String ret = time;
        try {
            if (!time.contains(".")) {
                time += ".0";
            }
            String as[] = time.split("\\.");
            String aa[] = as[0].split(":");
            ret = "";
            for (String s : aa) {
                if (s.length() == 1) {
                    s = "0" + s;
                }
                ret += s + " ";
            }
            ret = ret.trim();
            ret = ret.replace(" ", ":");
            if (as.length > 1) {
                ret += "." + as[1];
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 转换时间格式  00:00:00 => 0:0:0
     *
     * @param time
     * @return
     */
    public static String formatString_Hms(String time) {
        long tt = getLongTime(time);
        return getStringTime(tt);
    }



}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值