package com.Mrzhang.common.utils; import org.apache.commons.lang3.time.DateFormatUtils; import java.lang.management.ManagementFactory; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Random; /** * 时间工具类 * * */ public class DateUtils extends org.apache.commons.lang3.time.DateUtils { /** * 仅显示年月日,例如 2015-08-11. */ public static final String DATE_FORMAT = "yyyy-MM-dd"; /** * 显示年月日时分秒,例如 2015-08-11 09:51:53. */ public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; /** * 仅显示时分秒,例如 09:51:53. */ public static final String TIME_FORMAT = "HH:mm:ss"; public static String YYYY = "yyyy"; public static String YYYY_MM = "yyyy-MM"; public static String YYYY_MM_DD = "yyyy-MM-dd"; 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"}; /** * 每天的毫秒数 8640000. */ public static final long MILLISECONDS_PER_DAY = 86400000L; /** * 每周的天数. */ public static final long DAYS_PER_WEEK = 7L; /** * 每小时毫秒数. */ public static final long MILLISECONDS_PER_HOUR = 3600000L; /** * 每分钟秒数. */ public static final long SECONDS_PER_MINUTE = 60L; /** * 每小时秒数. */ public static final long SECONDS_PER_HOUR = 3600L; /** * 每天秒数. */ public static final long SECONDS_PER_DAY = 86400L; /** * 每个月秒数,默认每月30天. */ public static final long SECONDS_PER_MONTH = 2592000L; /** * 每年秒数,默认每年365天. */ public static final long SECONDS_PER_YEAR = 31536000L; /** * 获取当前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 getTimeOrder() { return parseDateToStr("YYYYMMDDHHMMSS", new Date()); } /** * 返回字符串类型的现在时间 * @return */ public static final String getStringDate() { return parseDateToStr("yyyy-MM-dd HH:mm:ss", new Date()); } public static final String getDateToString(Date date) { return parseDateToStr("yyyy-MM-dd HH:mm:ss", date); } public static final String dateTimeNow() { return dateTimeNow(YYYYMMDDHHMMSS); } public static final String sjdateTimeNow() { String s = dateTimeNow(YYYYMMDDHHMMSS); java.util.Random random=new java.util.Random(); // 返回0 to x的一个随机数但不会取到x,即返回[0,x)闭开区间的值。 int rn=random.nextInt(100); String s1 = String.valueOf(rn); return s+s1; } public static final String getDDHH() { return parseDateToStr("DDHH", new Date()); } 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); } } /** * 日期路径 即年/月/日 如2018/08/08 */ public static final String datePath() { Date now = new Date(); return DateFormatUtils.format(now, "yyyy/MM/dd"); } /** * 日期路径 即年/月/日 如20180808 */ public static final String dateTime() { Date now = new Date(); return DateFormatUtils.format(now, "yyyyMMdd"); } /** * 日期路径 即时:分:秒 如10:10:10 */ public static final String dateHHmmss() { Date now = new Date(); return DateFormatUtils.format(now, "HH:mm:ss"); } /** * 日期型字符串转化为日期 格式 */ public static Date parseDate(Object str) { if (str == null) { return null; } try { return parseDate(str.toString(), parsePatterns); } catch (ParseException e) { return null; } } /** * 日期型字符串转化为日期 格式 */ public static String parseString(Date str) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = formatter.format(str); return format; } public static String getYYYYMMDD(Date str) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); String format = formatter.format(str); return format; } /** * 获取服务器启动时间 */ public static Date getServerStartDate() { long time = ManagementFactory.getRuntimeMXBean().getStartTime(); return new Date(time); } /** * 计算两个时间差 */ 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 double getdatehour(String startDate, String endDate) throws ParseException { SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm"); Date fromDate2 = simpleFormat.parse(startDate); Date toDate2 = simpleFormat.parse(endDate); long from2 = fromDate2.getTime(); long to2 = toDate2.getTime(); int hours = (int) ((to2 - from2) / (1000 * 60 * 60)); return hours; } /** * 计算两个时间差分钟 */ public static int getdateminutes( String startDate,String endDate) throws ParseException { SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm"); Date fromDate3 = simpleFormat.parse(startDate); Date toDate3 = simpleFormat.parse(endDate); long from3 = fromDate3.getTime(); long to3 = toDate3.getTime(); int minutes = (int) ((to3 - from3) / (1000 * 60)); return minutes; } /** * 计算两个时间差天数 */ public static int getdateday( String startDate,String endDate) throws ParseException { SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); /*天数差*/ Date fromDate1 = simpleFormat.parse(startDate); Date toDate1 = simpleFormat.parse(endDate); long from1 = fromDate1.getTime(); long to1 = toDate1.getTime(); int days = (int) ((to1 - from1) / (1000 * 60 * 60 * 24)); return days; } /** * 时间戳 * @return */ public static String getTimestamp(){ Date date = new Date(); String timestamp = String.valueOf(date.getTime()); ; return timestamp; } public static int getCurrentMonthLastDay() { Calendar a = Calendar.getInstance(); a.set(Calendar.DATE, 1);//把日期设置为当月第一天 a.roll(Calendar.DATE, -1);//日期回滚一天,也就是最后一天 int maxDate = a.get(Calendar.DATE); return maxDate; } /** * 当天时间的前一天 * @return */ public static String getStringDateADD(String dates,Integer num) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); String stringDate = sdf.format(date); Calendar calendar = new GregorianCalendar(); calendar.setTime(date); if ("YEAR".equals(dates)) { //把日期往后增加一年,负数减一年 calendar.add(Calendar.YEAR, num); date = calendar.getTime(); stringDate = sdf.format(date); }else if ("MONTH".equals(dates)) { //把日期往后增加一个月,负数减一个月 calendar.add(Calendar.MONTH, num); date = calendar.getTime(); stringDate = sdf.format(date); }else if ("MONTH".equals(dates)) { //把日期往后增加一周,负数减一周 calendar.add(Calendar.WEEK_OF_MONTH, num); date = calendar.getTime(); stringDate = sdf.format(date); }else if ("DAY".equals(dates)) { //把日期往后增加一天,负数减一天 calendar.add(Calendar.DAY_OF_MONTH, num); date = calendar.getTime(); stringDate = sdf.format(date); } return stringDate; } /** * 当天时间的前一天 * @return */ public static String getStringDateymdhfADD(String dates,Integer num) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); String stringDate = sdf.format(date); Calendar calendar = new GregorianCalendar(); calendar.setTime(date); if ("YEAR".equals(dates)) { //把日期往后增加一年,负数减一年 calendar.add(Calendar.YEAR, num); date = calendar.getTime(); stringDate = sdf.format(date); }else if ("MONTH".equals(dates)) { //把日期往后增加一个月,负数减一个月 calendar.add(Calendar.MONTH, num); date = calendar.getTime(); stringDate = sdf.format(date); }else if ("MONTH".equals(dates)) { //把日期往后增加一周,负数减一周 calendar.add(Calendar.WEEK_OF_MONTH, num); date = calendar.getTime(); stringDate = sdf.format(date); }else if ("DAY".equals(dates)) { //把日期往后增加一天,负数减一天 calendar.add(Calendar.DAY_OF_MONTH, num); date = calendar.getTime(); stringDate = sdf.format(date); } return stringDate; } /** * 当天时间的前一天 * @return */ public static Date getDateADD(String dates,Integer num) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); String stringDate = sdf.format(date); Calendar calendar = new GregorianCalendar(); calendar.setTime(date); if ("YEAR".equals(dates)) { //把日期往后增加一年,负数减一年 calendar.add(Calendar.YEAR, num); date = calendar.getTime(); stringDate = sdf.format(date); }else if ("MONTH".equals(dates)) { //把日期往后增加一个月,负数减一个月 calendar.add(Calendar.MONTH, num); date = calendar.getTime(); stringDate = sdf.format(date); }else if ("MONTH".equals(dates)) { //把日期往后增加一周,负数减一周 calendar.add(Calendar.WEEK_OF_MONTH, num); date = calendar.getTime(); stringDate = sdf.format(date); }else if ("DAY".equals(dates)) { //把日期往后增加一天,负数减一天 calendar.add(Calendar.DAY_OF_MONTH, num); date = calendar.getTime(); stringDate = sdf.format(date); } Date date1 = parseDate(stringDate); return date1; } /** * 当天时间的前一天 * @return */ public static Date getDateADaaaD(String dates,Integer num,Date date) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String stringDate = sdf.format(date); Calendar calendar = new GregorianCalendar(); calendar.setTime(date); if ("YEAR".equals(dates)) { //把日期往后增加一年,负数减一年 calendar.add(Calendar.YEAR, num); date = calendar.getTime(); stringDate = sdf.format(date); }else if ("MONTH".equals(dates)) { //把日期往后增加一个月,负数减一个月 calendar.add(Calendar.MONTH, num); date = calendar.getTime(); stringDate = sdf.format(date); }else if ("MONTH".equals(dates)) { //把日期往后增加一周,负数减一周 calendar.add(Calendar.WEEK_OF_MONTH, num); date = calendar.getTime(); stringDate = sdf.format(date); }else if ("DAY".equals(dates)) { //把日期往后增加一天,负数减一天 calendar.add(Calendar.DAY_OF_MONTH, num); date = calendar.getTime(); stringDate = sdf.format(date); } Date date1 = parseDate(stringDate); return date1; } /** * 时间时分秒比大小 * @param t1 * @param t2 * @return */ public static int timeCompare(String t1,String t2){ SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); Calendar c1=Calendar.getInstance(); Calendar c2=Calendar.getInstance(); try { c1.setTime(formatter.parse(t1)); c2.setTime(formatter.parse(t2)); } catch (ParseException e) { e.printStackTrace(); } int result=c1.compareTo(c2); return result; } /** * 时间时分秒比大小 * @param t1 * @param t2 * @return */ public static int timeCompare(Date t1,Date t2){ SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); String format1 = formatter.format(t1); String format = formatter.format(t2); int result=format1.compareTo(format); return result; } /** * 随机返回时间 * @return */ public static String getDatetime(){ String datetime = null; Random rd = new Random(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); long ts = new Date().getTime()+6000*rd.nextInt(60)+600000*rd.nextInt(35); return datetime = df.format(ts); } /** * 随机返回下面的字符串 * @return */ public static String getCarBrand(){ String brand=""; Random rd = new Random(); String[] strs = {"大众","别克","丰田","吉利","宝马","丰田","丰田","标志"}; int num = rd.nextInt(strs.length); brand = strs[num]; return brand; } /** * 得到当前日期和时间字符串. * @return String 日期和时间字符串,例如 2015-08-11 09:51:53 * @since 1.0 */ public static String getDateTime() { return formatDate(new Date(), DateUtils.DATETIME_FORMAT); } /** * 获取当前时间指定格式下的字符串. * @param pattern * 转化后时间展示的格式,例如"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss"等 * @return String 格式转换之后的时间字符串. * @since 1.0 */ public static String getDate(String pattern) { return DateFormatUtils.format(new Date(), pattern); } /** * 获取指定日期的字符串格式. * @param date 需要格式化的时间,不能为空 * @param pattern 时间格式,例如"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss"等 * @return String 格式转换之后的时间字符串. * @since 1.0 */ public static String getDate(Date date, String pattern) { return DateFormatUtils.format(date, pattern); } /** * 获取日期时间字符串,默认格式为(yyyy-MM-dd). * @param date 需要转化的日期时间 * @param pattern 时间格式,例如"yyyy-MM-dd" "HH:mm:ss" "E"等 * @return String 格式转换后的时间字符串 * @since 1.0 */ public static String formatDate(Date date, Object... pattern) { String formatDate = null; if (pattern != null && pattern.length > 0) { formatDate = DateFormatUtils.format(date, pattern[0].toString()); } else { formatDate = DateFormatUtils.format(date, DateUtils.DATE_FORMAT); } return formatDate; } /** * 获取当前年份字符串. * @return String 当前年份字符串,例如 2015 * @since 1.0 */ public static String getYear() { return formatDate(new Date(), "yyyy"); } /** * 获取当前月份字符串. * @return String 当前月份字符串,例如 08 * @since 1.0 */ public static String getMonth() { return formatDate(new Date(), "MM"); } /** * 获取当前天数字符串. * @return String 当前天数字符串,例如 11 * @since 1.0 */ public static String getDay() { return formatDate(new Date(), "dd"); } /** * 获取当前星期字符串. * @return String 当前星期字符串,例如星期二 * @since 1.0 */ public static String getWeek() { return formatDate(new Date(), "E"); } /** * 获取当前日期与指定日期相隔的天数. * @param date 给定的日期 * @return long 日期间隔天数,正数表示给定日期在当前日期之前,负数表示在当前日期之后 * @since 1.0 */ public static long pastDays(Date date) { // 将指定日期转换为yyyy-MM-dd格式 date = DateUtils.parseDate(DateUtils.formatDate(date, DateUtils.DATE_FORMAT)); // 当前日期转换为yyyy-MM-dd格式 Date currentDate = DateUtils.parseDate(DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT)); long t=0; if(date!=null&¤tDate!=null){ t = (currentDate.getTime() - date.getTime()) / DateUtils.MILLISECONDS_PER_DAY; } return t; } /** * 获取当前日期指定天数之后的日期. * @param num 相隔天数 * @return Date 日期 * @since 1.0 */ public static Date nextDay(int num) { Calendar curr = Calendar.getInstance(); curr.set(Calendar.DAY_OF_MONTH, curr.get(Calendar.DAY_OF_MONTH) + num); return curr.getTime(); } /** * 获取当前日期指定月数之后的日期. * @param num 间隔月数 * @return Date 日期 * @since 1.0 */ public static Date nextMonth(int num) { Calendar curr = Calendar.getInstance(); curr.set(Calendar.MONTH, curr.get(Calendar.MONTH) + num); return curr.getTime(); } /** * 获取当前日期指定年数之后的日期. * @param num 间隔年数 * @return Date 日期 * @since 1.0 */ public static Date nextYear(int num) { Calendar curr = Calendar.getInstance(); curr.set(Calendar.YEAR, curr.get(Calendar.YEAR) + num); return curr.getTime(); } /** * 将 Date 日期转化为 Calendar 类型日期. * @param date 给定的时间,若为null,则默认为当前时间 * @return Calendar Calendar对象 * @since 1.0 */ public static Calendar getCalendar(Date date) { Calendar calendar = Calendar.getInstance(); // calendar.setFirstDayOfWeek(Calendar.SUNDAY);//每周从周日开始 // calendar.setMinimalDaysInFirstWeek(1); // 设置每周最少为1天 if (date != null) { calendar.setTime(date); } return calendar; } /** * 计算两个日期之间相差天数. * @param start 计算开始日期 * @param end 计算结束日期 * @return long 相隔天数 * @since 1.0 */ public static long getDaysBetween(Date start, Date end) { // 将指定日期转换为yyyy-MM-dd格式 start = DateUtils.parseDate(DateUtils.formatDate(start, DateUtils.DATE_FORMAT)); // 当前日期转换为yyyy-MM-dd格式 end = DateUtils.parseDate(DateUtils.formatDate(end, DateUtils.DATE_FORMAT)); long diff=0; if(start!=null&&end!=null) { diff = (end.getTime() - start.getTime()) / DateUtils.MILLISECONDS_PER_DAY; } return diff; } /** * 计算两个日期之前相隔多少周. * @param start 计算开始时间 * @param end 计算结束时间 * @return long 相隔周数,向下取整 * @since 1.0 */ public static long getWeeksBetween(Date start, Date end) { return getDaysBetween(start, end) / DateUtils.DAYS_PER_WEEK; } /** * 获取与指定日期间隔给定天数的日期. * @param specifiedDay 给定的字符串格式日期,支持的日期字符串格式包括"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss", * "yyyy-MM-dd HH:mm", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", * "yyyy/MM/dd HH:mm" * @param num 间隔天数 * @return String 间隔指定天数之后的日期 * @since 1.0 */ public static String getSpecifiedDayAfter(String specifiedDay, int num) { Date specifiedDate = parseDate(specifiedDay); Calendar c = Calendar.getInstance(); c.setTime(specifiedDate); int day = c.get(Calendar.DATE); c.set(Calendar.DATE, day + num); String dayAfter = formatDate(c.getTime(), DateUtils.DATE_FORMAT); return dayAfter; } /** * 计算两个日期之前间隔的小时数. * * @param date1 * 结束时间 * @param date2 * 开始时间 * @return String 相差的小时数,保留一位小数 * @since 1.0 */ public static String dateMinus(Date date1, Date date2) { if (date1 == null || date2 == null) { return "0"; } Long r = date1.getTime() - date2.getTime(); DecimalFormat df = new DecimalFormat("#.0"); double result = r * 1.0 / DateUtils.MILLISECONDS_PER_HOUR; return df.format(result); } /** * 获取当前季度 . * * @return Integer 当前季度数 * @since 1.0 */ public static Integer getCurrentSeason() { Calendar calendar = Calendar.getInstance(); Integer month = calendar.get(Calendar.MONTH) + 1; int season = 0; if (month >= 1 && month <= 3) { season = 1; } else if (month >= 4 && month <= 6) { season = 2; } else if (month >= 7 && month <= 9) { season = 3; } else if (month >= 10 && month <= 12) { season = 4; } return season; } /** * 将以秒为单位的时间转换为其他单位. * * @param seconds * 秒数 * @return String 例如 16分钟前、2小时前、3天前、4月前、5年前等 * @since 1.0 */ public static String getIntervalBySeconds(long seconds) { StringBuffer buffer = new StringBuffer(); if (seconds < SECONDS_PER_MINUTE) { buffer.append(seconds).append("秒前"); } else if (seconds < SECONDS_PER_HOUR) { buffer.append(seconds / SECONDS_PER_MINUTE).append("分钟前"); } else if (seconds < SECONDS_PER_DAY) { buffer.append(seconds / SECONDS_PER_HOUR).append("小时前"); } else if (seconds < SECONDS_PER_MONTH) { buffer.append(seconds / SECONDS_PER_DAY).append("天前"); } else if (seconds < SECONDS_PER_YEAR) { buffer.append(seconds / SECONDS_PER_MONTH).append("月前"); } else { buffer.append(seconds / DateUtils.SECONDS_PER_YEAR).append("年前"); } return buffer.toString(); } /** * * getNowTimeBefore(记录时间相当于目前多久之前) * * @param seconds * 秒 * @return * @exception @since * 1.0 * @author rlliu */ public static String getNowTimeBefore(long seconds) { StringBuffer buffer = new StringBuffer(); buffer.append("上传于"); if (seconds < 3600) { buffer.append((long) Math.floor(seconds / 60.0)).append("分钟前"); } else if (seconds < 86400) { buffer.append((long) Math.floor(seconds / 3600.0)).append("小时前"); } else if (seconds < 604800) { buffer.append((long) Math.floor(seconds / 86400.0)).append("天前"); } else if (seconds < 2592000) { buffer.append((long) Math.floor(seconds / 604800.0)).append("周前"); } else if (seconds < 31104000) { buffer.append((long) Math.floor(seconds / 2592000.0)).append("月前"); } else { buffer.append((long) Math.floor(seconds / 31104000.0)).append("年前"); } return buffer.toString(); } /** * * getMonthsBetween(查询两个日期相隔的月份) * * @param startDate 开始日期1 (格式yyyy-MM-dd) * @param endDate 截止日期2 (格式yyyy-MM-dd) * @return */ public static int getMonthsBetween(String startDate, String endDate) { Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); c1.setTime(DateUtils.parseDate(startDate)); c2.setTime(DateUtils.parseDate(endDate)); int year = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR); int month = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH); return Math.abs(year * 12 + month); } /** * * getDayOfWeek(获取当前日期是星期几) * * @param dateStr 日期 * @return 星期几 */ public static String getDayOfWeek(String dateStr) { String[] weekOfDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" }; Date date = parseDate(dateStr); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int num = calendar.get(Calendar.DAY_OF_WEEK) - 1; return weekOfDays[num]; } /** * sns 格式 如几秒前,几分钟前,几小时前,几天前,几个月前,几年后, ... 精细,类如某个明星几秒钟之前发表了一篇微博 * * @param createTime * @return */ public static String snsFormat(long createTime) { long now = System.currentTimeMillis() / 1000; long differ = now - createTime / 1000; String dateStr = ""; if (differ <= 60) { dateStr = "刚刚"; } else if (differ <= 3600) { dateStr = (differ / 60) + "分钟前"; } else if (differ <= 3600 * 24) { dateStr = (differ / 3600) + "小时前"; } else if (differ <= 3600 * 24 * 30) { dateStr = (differ / (3600 * 24)) + "天前"; } else { Date date = new Date(createTime); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); dateStr = sdf.format(date); } return dateStr; } /** * 得到UTC时间,类型为字符串,格式为"yyyy-MM-dd HH:mm" * 如果获取失败,返回null * @return */ public static String getUTCTimeStr() { StringBuffer UTCTimeBuffer = new StringBuffer(); // 1、取得本地时间: Calendar cal = Calendar.getInstance() ; // 2、取得时间偏移量: int zoneOffset = cal.get(java.util.Calendar.ZONE_OFFSET); // 3、取得夏令时差: int dstOffset = cal.get(java.util.Calendar.DST_OFFSET); // 4、从本地时间里扣除这些差量,即可以取得UTC时间: cal.add(java.util.Calendar.MILLISECOND, -(zoneOffset + dstOffset)); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); UTCTimeBuffer.append(year).append("-").append(month).append("-").append(day) ; UTCTimeBuffer.append(" ").append(hour).append(":").append(minute) ; try{ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); sdf.parse(UTCTimeBuffer.toString()) ; return UTCTimeBuffer.toString() ; }catch(ParseException e) { e.printStackTrace() ; } return null ; } /** * 生成随机时间 * * @param beginDate * @param endDate * @return */ public static Date randomDate(String beginDate, String endDate) { try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date start = format.parse(beginDate);// 构造开始日期 Date end = format.parse(endDate);// 构造结束日期 // getTime()表示返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。 if (start.getTime() >= end.getTime()) { return null; } long date = random(start.getTime(), end.getTime()); return new Date(date); } catch (Exception e) { e.printStackTrace(); } return null; } public static long random(long begin, long end) { long rtn = begin + (long) (Math.random() * (end - begin)); // 如果返回的是开始时间和结束时间,则递归调用本函数查找随机值 if (rtn == begin || rtn == end) { return random(begin, end); } return rtn; } /** * 取当前时间的年月 * @return */ public static String getYYMM(){ Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(YYYY_MM); String format = simpleDateFormat.format(date); return format; } /** * 取传入时间的年月 * @param date * @return */ public static String getYYMM(Date date){ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(YYYY_MM); String format = simpleDateFormat.format(date); return format; } /** * 取传入时间的年月日 * @param date * @return */ public static Date StringToDate(String date) throws ParseException { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(YYYY_MM_DD); Date format = simpleDateFormat.parse(date); return format; } /** * 取传入时间的时分秒 * @param date * @return */ public static String getHHMMSS(Date date){ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(TIME_FORMAT); String format = simpleDateFormat.format(date); return format; } /** * 取插入date类型的时间的上个月 * @param date * @return */ public static String getLastMonth(Date date) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM"); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); // 设置为当前时间 calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 设置为上一个月 date = calendar.getTime(); String accDate = format.format(date); return accDate; } /** * 取date类型的两个时间的相差小时数 * @param startDate * @param endDate * @return * @throws ParseException */ public static double getdatehour1(Date startDate, Date endDate) throws ParseException { long from2 = startDate.getTime(); long to2 = endDate.getTime(); int hours = (int) ((to2 - from2) / (1000 * 60 * 60)); return hours; } /** * 取date类型的两个时间的相差分钟数 * @param startDate * @param endDate * @return * @throws ParseException */ public static int getdateminutess( Date startDate,Date endDate) throws ParseException { long from3 = startDate.getTime(); long to3 = endDate.getTime(); int minutes = (int) ((to3 - from3) / (1000 * 60)); return minutes; } /** * 取String类型的两个时间的相差分钟数 * @param startDate * @param endDate * @return * @throws ParseException */ public static int getdateminutea( String startDate,String endDate) throws ParseException { SimpleDateFormat simpleFormat = new SimpleDateFormat("hh:mm:ss"); Date fromDate3 = simpleFormat.parse(startDate); Date toDate3 = simpleFormat.parse(endDate); long from3 = fromDate3.getTime(); long to3 = toDate3.getTime(); int minutes = (int) ((to3 - from3) / (1000 * 60)); return minutes; } /** * 获取当前月份字符串. * @return String 当前月份字符串,例如 08 * @since 1.0 */ public static String getMonthMY(Date date) { return formatDate(date, "HH"); }
/** *合同更换计算剩余时间 * @param StarTime * @param EndTime * @return */ public static int between(Date StarTime,Date EndTime){ //相差几个月 Calendar instance = Calendar.getInstance(); Calendar instance2 = Calendar.getInstance(); instance.setTime(EndTime); //当前年 int YEAR = instance.get(Calendar.YEAR); //当前月 int MONTH = instance.get(Calendar.MONTH) + 1; //当前日 int DATE = instance.get(Calendar.DAY_OF_MONTH); instance2.setTime(StarTime); //合同开始年 int StarYear = instance2.get(Calendar.YEAR); //合同开始月 int StarMONTH= instance2.get(Calendar.MONTH) + 1; //合同开始日 int StarDAY = instance2.get(Calendar.DAY_OF_MONTH); String between = DateUtils.DateDifference(StarYear, StarMONTH, StarDAY, YEAR, MONTH, DATE); String[] split = between.split(","); String s1 = split[0]; String s2 = split[1]; String s3 = split[2]; int betweenYear = Integer.parseInt(s1); int betweenMONTH = Integer.parseInt(s2); int betweenDATE = Integer.parseInt(s3); int newMONTH=betweenMONTH; int a=0; if(betweenYear>0){ a=betweenYear*12; newMONTH=newMONTH+a; }if(betweenDATE>0){ newMONTH= newMONTH+1; } System.out.println(newMONTH+"==================================="); return newMONTH; }
public static String DateDifference(int StarYear, int StarMonth, int StarDayOfMonth,int endYear,int endMonth, int endDayOfMonth) { LocalDate oldDate = LocalDate.of(endYear,endMonth,endDayOfMonth); System.out.println("oldDate:" + oldDate); LocalDate today = LocalDate.of(StarYear, StarMonth, StarDayOfMonth); System.out.println("today:" + today); Period p = Period.between(today,oldDate); int months = p.getMonths(); int days = p.getDays(); String newYears=null; String newMonths=null; String newDays=null; if(months<10){ newMonths="0"+months; }else { newMonths= String.valueOf(months); } if(days<10){ newDays ="0"+days; }else { newDays= String.valueOf(months); }
}