获取时间的工具类

1.生成12位的授权码

/**
 * 生成12位的授权码
 * @param maxLeng
 * @return
 */
public static String generateKey(int maxLeng) {
    final int maxNum = 41;
    int i; // 生成的随机数
    int count = 0; // 生成的密码的长度
    char[] str = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
            't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '!', '@', '#', '$',
            '*' };
    StringBuffer key = new StringBuffer("");
    Random r = new Random();
    while (count < maxLeng) {
        // 生成随机数,取绝对值,防止生成负数,
        i = Math.abs(r.nextInt(maxNum)); // 生成的数最大为36-1
        if (i >= 0 && i < str.length) {
            key.append(str[i]);
            count++;
        }
    }
    return key.toString();
}

2.获取下个月的今天是几月几号

/**
 * 获取下个月的今天是几月几号
 * 格式:MM-dd
 * @return
 */
public static String getNextMonth() {
    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
    Calendar calendar = Calendar.getInstance(); 
    calendar.setTime(new Date());
    calendar.add(Calendar.MONTH,1);
    return sdf.format(calendar.getTime());
}

3.获取明天是几月几号

/**
 * 获取明天是几月几号
 * 格式:MM-dd
 * @return
 */
public static String getTomorrow() {
    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
    Calendar calendar = Calendar.getInstance(); 
    calendar.setTime(new Date());
    calendar.add(Calendar.DATE,1);
    return sdf.format(calendar.getTime());
}

4.获取昨天是几月几号

/**
 * 获取昨天是几月几号
 * 格式:MMdd
 * @return
 */
public static String getYesterday() {
    SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
    Date date = new Date();
    Long as = Long.valueOf(sdf.format(date)) - 1;
    String Yester = String.valueOf(as);
    return Yester;
}

5.计算某个日期几秒之后的时间

/**
 * 计算某个日期几秒之后的时间
 * @param minute
 * @return
 */
public static String getSomeTimeBySecond(String time,int second) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Calendar calendar = Calendar.getInstance();
    try {
        calendar.setTime(sdf.parse(time));
        calendar.add(Calendar.SECOND, second);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
}

6.某个日期的几天后的时间的时间

/**
 * 某个日期的几天后
 * @param time
 * @param days
 * @return
 */
public static String getSomeDayBefore(String time,Integer days){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar now = Calendar.getInstance();
    try {
        now.setTime(sdf.parse(time));
        System.out.println(now.getTime());
        now.set(Calendar.DATE, now.get(Calendar.DATE) + days);
        System.out.println(sdf.format(now.getTime()));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sdf.format(now.getTime());
}

7.某个日期几个月后的时间

/**
 * 某个日期几个月后
 * @param time
 * @param days
 * @return
 */
public static String getSomeMonthBefore(String time,Integer days){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar now = Calendar.getInstance();
    try {
        now.setTime(sdf.parse(time));
        System.out.println(now.getTime());
        now.set(Calendar.MONTH, now.get(Calendar.MONTH) + days);
        System.out.println(sdf.format(now.getTime()));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sdf.format(now.getTime());
}

8.日期和字符串互转

/**
 * YYYY_MM_dd转日期
 * 格式:MMdd
 * @return
 */
public static String datetoYYYY_MM_dd(String date) {
    SimpleDateFormat formerSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String dateString=null;
    try {
        dateString = sdf.format(formerSDF.parse(date));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return dateString;
}

/**
 * 日期转时间戳
 * @param date
 * @return
 */
public static String date2TimeStamp(String date){
    try {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return String.valueOf(sdf.parse(date).getTime()/1000);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

/**
 * 时间戳转日期
 * @param date
 * @return
 */
public static String timeStamp2Date(String date){
    try {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date(Long.valueOf(date+"000")));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

9.与当前时间相差几分钟

/**
 * 与当前时间相差几分钟
 * @param nowDate
 * @return
 */
public static Long getTwoDateMin(String nowDate) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
        Date nowDate1 = dateFormat.parse(nowDate);
        Date date = new Date();
        long diff = date.getTime() - nowDate1.getTime();
        long min = diff/60/1000;
        return min;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

10. 获得上个月月份年份

/**
 * 获得上个月月份年份
 * @return
 */
public static String getYearMonth() {
    Calendar now = Calendar.getInstance();
    int month = now.get(Calendar.MONTH);
    String m;
    if (month < 10) {
        m = "0" + month;
    } else {
        m = month + "";
    }
    return now.get(Calendar.YEAR) + "-" + m;
}

11.获取当前时间

/**
 * 获取年月日
 * 格式:yyyyMMdd  HHmmss  yyyy-MM-dd  MM-dd  MMdd  yyyy-MM  yyyy-MM-dd HH:mm:ss
 * @param days
 * @return
 */
public static String getYYYYMMdd() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    Date date = new Date();
    return sdf.format(date);
}

12.返回两个日期之差 相差天数

/**
 * 时间比较大小 
 * 时间格式:yyyy-MM-dd
 * @param startDate
 * @param endDate
 * @return 返回秒数
 * @throws ParseException
 */
public static int daysBetween(Date startDate,Date endDate) throws ParseException {    
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
    startDate = sdf.parse(sdf.format(startDate));  
    endDate = sdf.parse(sdf.format(endDate));  
    Calendar cal = Calendar.getInstance();
    cal.setTime(startDate);    
    long time1 = cal.getTimeInMillis();                 
    cal.setTime(endDate);    
    long time2 = cal.getTimeInMillis();         
    long between_days=(time2-time1)/(1000*3600*24);  
    return Integer.parseInt(String.valueOf(between_days));           
} 

/**
 * 返回两个日期之差 
 * @param backMonthNum
 * @return
 */
public static Integer getDateNum(Date startTime,Date endTime) {
    try {
        Integer dateNum = (int) ((endTime.getTime() - startTime.getTime()) / (1000*3600*24));
        return dateNum;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
/** * 返回传入日期与当前时间的日期相差天数 * @param backMonthNum * @return */ public static Integer getDateNum(String time) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); try { Date now = dateFormat.parse(dateFormat.format(new Date())); Date compareTime = dateFormat.parse(time); int dateNum = (int) ((compareTime.getTime() - now.getTime()) / (1000*3600*24)); return dateNum; } catch (Exception e) { e.printStackTrace(); return null; } } /** * 返回两个日期相差天数 * @param backMonthNum * @return */ public static Integer getTwoDateNum(String startTime,String endTime) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); try { Date startDate = dateFormat.parse(startTime); Date endDate = dateFormat.parse(endTime); int dateNum = (int) ((endDate.getTime() - startDate.getTime()) / (1000*3600*24)); return dateNum; } catch (Exception e) { e.printStackTrace(); return null; } } /** * 时间string格式 比大小当createDate小于toDate时返回true,反之为false * @param createDate * @param toDate * @return * @throws ParseException */ public static boolean daysContrast(String createDate,String toDate) throws ParseException { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date create=df.parse(createDate); Date todates=df.parse(toDate); return create.before(todates); } /** * 时间Date格式 比大小当createDate小于toDate时返回true,反之为false * @param createDate * @param toDate * @return * @throws ParseException */ public static boolean daysDateContrast(Date createDate,Date toDate) throws ParseException { return createDate.before(toDate); }

13.计算2个日期之间相差的  相差多少年月日

/**
 * 计算2个日期之间相差的  相差多少年月日
 * 比如:2011-02-02 到  2017-03-02 相差 6年,1个月,0天
 * @param fromDate
 * @param toDate
 * @return
 */
public static int dayComparePrecise(String startTime,String toTime){
    int days = 0;
    try {
        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        long from = simpleFormat.parse(startTime).getTime();
        long to = simpleFormat.parse(toTime).getTime();
        days = (int) ((to - from)/(1000 * 60 * 60 * 24));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return days;
}

14.将格式yyyy-MM-dd转成yyyyMMdd

/**
 * 将格式yyyy-MM-dd转成yyyyMMdd
 * @param time
 * @return 
 */
public static String getYYYYMMdd(String time) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat othersdf = new SimpleDateFormat("yyyyMMdd");
    Date date=null;
    try {
        date = sdf.parse(time);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return othersdf.format(date);
}
/**
 * YYYY_MM_dd转日期
 * 格式:MMdd
 * @return
 */
public static Date YYYY_MM_ddToDate(String dateString) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date date=null;
    try {
        date = sdf.parse(dateString);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date;
}

/**
 * YYYY_MM_dd转日期
 * 格式:MMdd
 * @return
 */
public static String datetoYYYY_MM_dd(Date date) {
    if (date==null){
        return null;
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String dateString=null;
    dateString = sdf.format(date);
    return dateString;
}

15.返回当天时间的前几个月的时间

/**当前时间20180712,下个月时间为20180812
 * @param time 传入的开始时间
 * @param backMonthNum 相差的月数
 * @return 返回的时间格式:yyyy-MM-dd
 */
public static String getMonthDay(String time,Integer monthNum) {
    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date=dateFormat.parse(time);
        //Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date); // 设置为传入时间
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + monthNum); //设置正数为下几个月,负数为前几个月
        date = calendar.getTime();
        return dateFormat.format(date);
    } catch (Exception e) {
        e.printStackTrace();
        return "";
    }
}

 

/**
 * 几天后时间
 * 格式:yyyy-MM-dd
 * @param days
 * @return
 */
public static String getDaysLater(Integer days){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar now = Calendar.getInstance();
    now.setTime(new Date());
    now.set(Calendar.DATE, now.get(Calendar.DATE) + days);
    return sdf.format(now.getTime());
}

/**
 * 几天前时间
 * 格式:yyyy-MM-dd
 * @param days
 * @return
 */
public static String getDaysBefore(Integer days){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar now = Calendar.getInstance();
    now.setTime(new Date());
    now.set(Calendar.DATE, now.get(Calendar.DATE) - days);
    return sdf.format(now.getTime());
}

16.

/*
 * 获取指定日期下个月的第一天
 * @param dateStr
 * @param format
 * @return
 */
public static String getFirstDayOfNextMonth(String dateStr, String format) {
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    try {
        Date date = sdf.parse(dateStr);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1); // 设置为下几个月
        return sdf.format(calendar.getTime());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

/**
 * 当前时间加几个小时
 * @param hour
 * @return
 */
public static Date currDateAddHour(Double hour){
    long currentTime = new Date().getTime();
    currentTime += hour *60*60*1000;
    Date date=new Date(currentTime);
    return date;
}

/**
 * 计算几分钟之后的时间
 * @param minute
 * @return
 */
public static String getTimeByMinute(int minute) {
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MINUTE, minute);
    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
}

17.

/**
 * 得到几天后的时间
 * @param format:yyyy-MM-dd
 * @param day
 * @return
 */
public static String getDateAfter(int day,String format) {
    SimpleDateFormat sf = new SimpleDateFormat(format);
    Calendar c = Calendar.getInstance();
    c.add(Calendar.DAY_OF_MONTH, day);
    return sf.format(c.getTime());
}

18.

/**
 * 得到几天后的时间
 * @param d
 * @param day
 * @return
 * @throws ParseException 
 */
public static String getAfterDay(String time,int day){
    // 时间表示格式可以改变,yyyyMMdd需要写例如20160523这种形式的时间
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String str = time;
    // 将字符串的日期转为Date类型,ParsePosition(0)表示从第一个字符开始解析
    Date date = sdf.parse(str, new ParsePosition(0));
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    // add方法中的第二个参数n中,正数表示该日期后n天,负数表示该日期的前n天
    calendar.add(Calendar.DATE, day);
    Date date1 = calendar.getTime();
    String out = sdf.format(date1);
    return out;
}

18.

/**
 * 当前时间 - createTime 小于 3分钟
 * 比如:2011-02-02 到  2017-03-02 相差 6年,1个月,0天
 * @return
 */
public static long diffMin(String createTime){
    long minutes = 0l;
    try {
          DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
          Date d1 = df.parse(createTime);  
          Date d2 = new Date();
          long diff = d2.getTime() - d1.getTime();//这样得到的差值是毫秒级别  
          long days = diff / (1000 * 60 * 60 * 24);  
          long hours = (diff-days*(1000 * 60 * 60 * 24))/(1000* 60 * 60);  
          minutes = (diff-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60))/(1000* 60);  
          System.out.println(""+days+"天"+hours+"小时"+minutes+"分");  
    } catch (Exception e) {
        e.printStackTrace();
    }
    return minutes;
}

19.与当前时间比较大小

/**
 * 与当前时间比较大小
 * @param time 格式:yyyy-MM-dd
 * @param type gt大于 lt小于 
 * @return false or true
 */
public static boolean compareNow(String time,String type){
    Date now = new Date();
    try {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        now=sdf.parse(sdf.format(now));
        Date timeDate=sdf.parse(time);
        if("gt".equals(type)){
            if(timeDate.after(now)){//大于等于当前时间
                return true;
            }
        }else if("gte".equals(type)){
            if(timeDate.after(now)||sdf.format(now).equals(time)){//大于等于当前时间
                return true;
            }
        }else if("lte".equals(type)){
            if(now.after(timeDate)||sdf.format(now).equals(time)){//小于
                return true;
            }
        }else{
            if(now.after(timeDate)){//小于
                return true;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return false;
}

/**
 * 与当前时间比较大小
 * @param time 格式:yyyy-MM-dd
 * @param type gt大于 lt小于 
 * @return false or true
 */
public static boolean compareNowYMDHMS(String time,String type){
    Date now = new Date();
    try {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        now=sdf.parse(sdf.format(now));
        Date timeDate=sdf.parse(time);
        if("gt".equals(type)){
            if(timeDate.after(now)){//大于当前时间
                return true;
            }
        }else{
            if(now.after(timeDate)){//小于
                return true;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return false;
}
public static String diffMonthAndDay(Date startDate, Date endDate){
    Calendar calS = Calendar.getInstance();
    calS.setTime(startDate);
    int startY = calS.get(Calendar.YEAR);
    int startM = calS.get(Calendar.MONTH);
    int startD = calS.get(Calendar.DATE);
    int startDayOfMonth = calS.getActualMaximum(Calendar.DAY_OF_MONTH);
    
    calS.setTime(endDate);
    int endY = calS.get(Calendar.YEAR);
    int endM = calS.get(Calendar.MONTH);
    //处理2011-01-10到2011-01-10,认为服务为一天
    int endD = calS.get(Calendar.DATE)+1;
    int endDayOfMonth = calS.getActualMaximum(Calendar.DAY_OF_MONTH);
    
    StringBuilder sBuilder = new StringBuilder();
    if (endDate.compareTo(startDate)<0) {
        return sBuilder.append("过期").toString();
    }
    int lday = endD-startD;
    if (lday<0) {
        endM = endM -1;
        lday = startDayOfMonth+ lday;
    }
    //处理天数问题,如:2011-01-01 到    2013-12-31     2年11个月31天     实际上就是3年
    if (lday == endDayOfMonth) {
        endM = endM+1;
        lday =0;
    }
    int mos = (endY - startY)*12 + (endM- startM);
    int lyear = mos/12;
    int lmonth = mos%12;
    if (lyear >0) {
        lmonth+=lyear*12;
    }
    if (lmonth > 0) {
        sBuilder.append(lmonth+"个月");
    }
    if (lday >0 ) {
        sBuilder.append(lday+"天");
    }
    return sBuilder.toString();
}

public static Map<String, String> diffDate(Date startDate, Date endDate){
    Map<String, String> result=new HashMap<String, String>(); 
    try {
        Calendar calS = Calendar.getInstance();
        calS.setTime(startDate);
        int startY = calS.get(Calendar.YEAR);
        int startM = calS.get(Calendar.MONTH);
        int startD = calS.get(Calendar.DATE);
        int startDayOfMonth = calS.getActualMaximum(Calendar.DAY_OF_MONTH);
        
        calS.setTime(endDate);
        int endY = calS.get(Calendar.YEAR);
        int endM = calS.get(Calendar.MONTH);
        //处理2011-01-10到2011-01-10,认为服务为一天
        int endD = calS.get(Calendar.DATE)+1;
        int endDayOfMonth = calS.getActualMaximum(Calendar.DAY_OF_MONTH);
        
        if (endDate.compareTo(startDate)<0) {
            return result;
        }
        int lday = endD-startD;
        if (lday<0) {
            endM = endM -1;
            lday = startDayOfMonth+ lday;
        }
        //处理天数问题,如:2011-01-01 到    2013-12-31     2年11个月31天     实际上就是3年
        if (lday == endDayOfMonth) {
            endM = endM+1;
            lday =0;
        }
        int mos = (endY - startY)*12 + (endM- startM);
        int lyear = mos/12;
        int lmonth = mos%12;
        if (lyear >0) {
            lmonth+=lyear*12;
        }
        if (lmonth > 0) {
            result.put("month", lmonth+"");
        }
        if (lday >0 ) {
            result.put("day", lday+"");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}


public static Map<String, String> diffDate2(String reverifyTime,Integer timeValue,Integer nowPeriod){
    Map<String, String> result=new HashMap<String, String>();
    if(timeValue-nowPeriod>0){
        result.put("month", timeValue-nowPeriod+"");
    }

    String endDate=getMonthDay(reverifyTime,nowPeriod);
    String formerDate=getMonthDay(reverifyTime,nowPeriod-1);
    System.out.println("endDate--->"+endDate);
    System.out.println("formerDate"+formerDate);
    System.out.println("getTwoDateNum-->"+getTwoDateNum(formerDate,getYYYY_MM_dd()));
    if(getTwoDateNum(formerDate,getYYYY_MM_dd())<0){
        //如果上次应回款时间比现在时间大的话,则为提前还款,那么天数
        Integer dateNum=getTwoDateNum(formerDate,endDate);
        result.put("day", dateNum+"");
    }else{
        Integer dateNum=getTwoDateNum(getYYYY_MM_dd(),endDate);
        if(dateNum>0){
            result.put("day", dateNum+"");
        }
    }
    return result;
}

 

转载于:https://www.cnblogs.com/gjq1126-web/p/11206067.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值