java时间工具类

作者: Leslie_Lee | 来源:发表于2020-08-25 11:18 被阅读0次

    package com.donghui.oa.util;

    import java.text.DateFormat;

    import java.text.ParseException;

    import java.text.SimpleDateFormat;

    import java.util.Calendar;

    import java.util.Date;

    import java.util.GregorianCalendar;

    import java.util.TimeZone;

    import org.apache.commons.lang.StringUtils;

    /**

    * 时间工具类

    *

    * @author Fangpc

    *

    */

    public class DateUtils{

      /** 定义常量 **/

      public static final StringDATE_JFP_STR ="yyyyMM";

    public static final StringDATE_COLS_STR ="yyyyMMdd";

    public static final StringDATE_FULL_STR ="yyyy-MM-dd HH:mm:ss";

    public static final StringDATE_SMALL_STR ="yyyy-MM-dd";

    public static final StringDATE_KEY_STR ="yyMMddHHmmss";

    public static final StringDATETIME_KEYS_STR ="yyMMddHHmmssSSS";

    public static final StringDATE_FORMAT_ONE ="yyyy.MM.dd";

    public static final StringDATE_FORMAT_TWO ="yyyy-MM-dd";

    // 一天的毫秒数86400000 = 24*60*60*1000;

      private static final int millisPerDay =86400000;

    // 一小时的毫秒数3600000 = 24*60*60*1000;

      private static final int millisPerHour =3600000;

    /**

        * 格式化时间

        *

        * @param strDate

        * @return

        */

      public static String format(Date strDate) {

          SimpleDateFormat format =new SimpleDateFormat(DATE_FULL_STR);

    return format.format(strDate);

    }

      /**

        * 格式化时间

        *

        * @param strDate

        * @return

        */

      public static String format(Date strDate, String pattern) {

          SimpleDateFormat format =new SimpleDateFormat(pattern);

    return format.format(strDate);

    }

      /**

        * 使用预设格式提取字符串日期

        *

        * @param strDate

        *            日期字符串

        * @return

        */

      public static Date parse(String strDate) {

          return parse(strDate,DATE_FULL_STR);

    }

      /**

        * 使用用户格式提取字符串日期

        *

        * @param strDate

        *            日期字符串

        * @param pattern

        *            日期格式

        * @return

        */

      public static Date parse(String strDate, String pattern) {

          SimpleDateFormat df =new SimpleDateFormat(pattern);

    try {

            return df.parse(strDate);

    } catch (ParseException e) {

            e.printStackTrace();

    return null;

    }

    }

      /**

        * 两个时间比较

        *

        * @param date1

        * @return

        */

      public static int compareDateWithNow(Date date1) {

          Date date2 =new Date();

    int rnum = date1.compareTo(date2);

    return rnum;

    }

      /**

        * 两个时间比较(时间戳比较)

    *

        * @param date1

        * @return

        */

      public static int compareDateWithNow(long date1) {

          long date2 =dateToUnixTimestamp();

    if (date1 > date2) {

            return 1;

    } else if (date1 < date2) {

            return -1;

    } else {

            return 0;

    }

    }

      /**

        * 二个时间比较()

    *

        * @param DATE1

        * @param DATE2

        * @return 1:前面大于后面

        */

      public static int compareDate(String DATE1, String DATE2) {

          DateFormat df =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    try {

            Date dt1 = df.parse(DATE1);

    Date dt2 = df.parse(DATE2);

    if (dt1.getTime() > dt2.getTime()) {

                return 1;

    } else if (dt1.getTime() < dt2.getTime()) {

                return -1;

    } else {

                return 0;

    }

          } catch (Exception exception) {

            exception.printStackTrace();

    }

          return 0;

    }

      /**

        * 计算时间差 (时间单位,开始时间,结束时间) 调用方法 howLong("h","2007-08-09 10:22:26","2007-08-09

        * 20:21:30") ///9小时56分 返回9小时

        */

      public static long howLong(String unit, String time1, String time2) throws ParseException{

          // 时间单位(如:不足1天(24小时) 则返回0),开始时间,结束时间

          Date date1 =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time1);

    Date date2 =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time2);

    long ltime = date1.getTime() - date2.getTime() <0 ? date2.getTime() - date1.getTime()

                : date1.getTime() - date2.getTime();

    if ("s".equals(unit)) {

            return ltime /1000;// 返回秒

          } else if ("m".equals(unit)) {

            return ltime /60000;// 返回分钟

          } else if ("h".equals(unit)) {

            return ltime /millisPerHour;// 返回小时

          } else if ("d".equals(unit)) {

            return ltime /millisPerDay;// 返回天数

          } else {

            return 0;

    }

    }

      /**

        * 获取系统当前时间

        *

        * @return

        */

      public static String getNowTime() {

          SimpleDateFormat df =new SimpleDateFormat(DATE_FULL_STR);

    return df.format(new Date());

    }

      /**

        * 获取系统当前时间

        *

        * @return

        */

      public static String getNowTime(String type) {

          SimpleDateFormat df =new SimpleDateFormat(type);

    return df.format(new Date());

    }

      /**

        * 获取系统当前计费期

        *

        * @return

        */

      public static String getJFPTime() {

          SimpleDateFormat df =new SimpleDateFormat(DATE_JFP_STR);

    return df.format(new Date());

    }

      /**

        * 将指定的日期转换成Unix时间戳

        *

        * @param date

        *            date 需要转换的日期 yyyy-MM-dd HH:mm:ss

        * @return long 时间戳

        */

      public static long dateToUnixTimestamp(String date) {

          long timestamp =0;

    try {

            timestamp =new SimpleDateFormat(DATE_FULL_STR).parse(date).getTime();

    } catch (ParseException e) {

            e.printStackTrace();

    }

          return timestamp;

    }

      /**

        * 将指定的日期转换成Unix时间戳

        *

        * @param dateFormat

        *            date 需要转换的日期 yyyy-MM-dd

        * @return long 时间戳

        */

      public static long dateToUnixTimestamp(String date, String dateFormat) {

          long timestamp =0;

    try {

            timestamp =new SimpleDateFormat(dateFormat).parse(date).getTime();

    } catch (ParseException e) {

            e.printStackTrace();

    }

          return timestamp;

    }

      /**

        * 将当前日期转换成Unix时间戳

        *

        * @return long 时间戳

        */

      public static long dateToUnixTimestamp() {

          long timestamp = System.currentTimeMillis();

    return timestamp;

    }

      /**

        * 将Unix时间戳转换成日期

        *

        * @param timestamp

        *            timestamp 时间戳

        * @return String 日期字符串

        */

      public static String unixTimestampToDate(long timestamp) {

          if (timestamp ==0) {

            return null;

    }

          SimpleDateFormat sd =new SimpleDateFormat(DATE_FULL_STR);

    sd.setTimeZone(TimeZone.getTimeZone("GMT+8"));

    return sd.format(new Date(timestamp));

    }

      /**

        * 获取本月最后一天

        *

        * @return

        */

      public static String getDateByMonth(String dateType) {

          Calendar calendar = Calendar.getInstance();

    // 设置时间,当前时间不用设置

          // calendar.setTime(new Date());

          // 设置日期为本月最大日期

          calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));

    SimpleDateFormat format =new SimpleDateFormat(dateType);

    return format.format(calendar.getTime());

    }

      /**

        * 当月第一天

        *

        * @return

        */

      public static String getFirstDay(String dateType) {

          SimpleDateFormat format =new SimpleDateFormat(dateType);

    Calendar calendar = Calendar.getInstance();

    Date theDate = calendar.getTime();

    GregorianCalendar gcLast =(GregorianCalendar) Calendar.getInstance();

    gcLast.setTime(theDate);

    gcLast.set(Calendar.DAY_OF_MONTH,1);

    return format.format(gcLast.getTime());

    }

      /**

        * 时间相加

        * @param beginTime

        * @param minute

        * @return

        */

      public static Date addMinuteTime(Date beginTime, Integer minute) {

          Calendar cal = Calendar.getInstance();

    cal.setTime(beginTime);

    cal.add(Calendar.MINUTE, minute);

    Date endTime = cal.getTime();

    return endTime;

    }

      /**

        * 获取本周的周一 或周五 true 周一 false 周五

        *

        * @param isStart

        * @return

        */

      public static Date getWeekDay(boolean isStart) {

          Calendar clen = Calendar.getInstance();

    clen.add(Calendar.DAY_OF_MONTH,7);

    return getLastWeekDay(isStart, clen.getTime());

    }

      /**

        * 获取上周的周一或周五

        *

        * @param isStart

        * @param date

        * @return

        */

      public static Date getLastWeekDay(boolean isStart, Date date) {

          Calendar clen = Calendar.getInstance();

    if (date !=null) {

            clen.setTime(date);

    }

          clen.add(Calendar.DAY_OF_MONTH, -7);

    int ss = clen.get(Calendar.DAY_OF_WEEK);

    if (!isStart) {

            clen.add(Calendar.DAY_OF_MONTH, -(ss -6));

    return clen.getTime();

    }

          clen.add(Calendar.DAY_OF_MONTH, -(ss -2));

    return clen.getTime();

    }

      public static Date timeToZero(Date date) {

          Calendar clen = Calendar.getInstance();

    if (date !=null) {

            clen.setTime(date);

    }

          clen.set(Calendar.HOUR_OF_DAY,0);

    clen.set(Calendar.MINUTE,0);

    clen.set(Calendar.SECOND,0);

    return clen.getTime();

    }

      public static Date timeToMax(Date date) {

          Calendar clen = Calendar.getInstance();

    if (date !=null) {

            clen.setTime(date);

    }

          clen.set(Calendar.HOUR_OF_DAY,23);

    clen.set(Calendar.MINUTE,59);

    clen.set(Calendar.SECOND,59);

    return clen.getTime();

    }

      /**

        * 检查指定时间是否为周末

        *

        * @param date

        * @return

        */

      public static boolean dateIsWeekend(Date date) {

          boolean bool =false;

    try {

            Calendar cal = Calendar.getInstance();

    cal.setTime(new Date());

    if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY

                  || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {

                bool =true;

    }

          } catch (Exception e) {

            e.printStackTrace();

    }

          return bool;

    }

      /**

        * 获取下一年的日期

        *

        * @param dateType

        * @return

        */

      public static String getLastYear(String firstDay, String dateType) {

          SimpleDateFormat format =new SimpleDateFormat(dateType);

    Calendar calendar =new GregorianCalendar();

    try {

            calendar.setTime(format.parse(firstDay));

    calendar.add(Calendar.YEAR,1);// 把日期往后增加一年.整数往后推,负数往前移动

            calendar.add(Calendar.DATE, -1);// 把日期在往后减一天

          } catch (ParseException e) {

            e.printStackTrace();

    }

          return format.format(calendar.getTime());

    }

      /**

        * 毫秒转换天数 mss 毫秒数

        */

      public static String stmpToDate(Long mss) {

          int days =(int) (mss /(1000 *60 *60 *24));

    int hours =(int) ((mss %(1000 *60 *60 *24)) /(1000 *60 *60));

    int minutes =(int) ((mss %(1000 *60 *60)) /(1000 *60));

    return (days >0 ?(days +" 天 ") :"") +(hours >0 ?(hours +" 小时 ") :"") + minutes +" 分钟 ";

    }

      /**

        * 计算两个时间间隔

        *

        * @param str1

        * @param str2

        * @return

        */

      public static String getDistanceTime(String str1, String str2) {

          DateFormat df =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Date one;

    Date two;

    long day =0;

    long hour =0;

    long min =0;

    long sec =0;

    try {

            one = df.parse(str1);

    two = df.parse(str2);

    long time1 = one.getTime();

    long time2 = two.getTime();

    long diff;

    if (time1 < time2) {

                diff = time2 - time1;

    } else {

                diff = time1 - time2;

    }

            day = diff /(24 *60 *60 *1000);

    hour =(diff /(60 *60 *1000) - day *24);

    min =((diff /(60 *1000)) - day *24 *60 - hour *60);

    sec =(diff /1000 - day *24 *60 *60 - hour *60 *60 - min *60);

    } catch (ParseException e) {

            e.printStackTrace();

    }

          // return day + "天" + hour + "小时" + min + "分" + sec + "秒";

          return day +"天" + hour +"小时" + min +"分";

    }

      /**

        * 指定时间到当前时间的间隔

        *

        * @param str1

        * @return

        */

      public static long curentTimeDiffMin(String str1) {

          if(StringUtils.isBlank(str1)){

            return 0;

    }

          DateFormat df =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Date one;

    long min =0;

    try {

            one = df.parse(str1);

    long time1 = one.getTime();

    long time2 =new Date().getTime();

    long diff;

    if (time1 < time2) {

                diff = time2 - time1;

    } else {

                diff = time1 - time2;

    }

            min = diff /(60 *1000);

    } catch (ParseException e) {

            e.printStackTrace();

    }

          return min;

    }

      /**

        * 两个日期时间的间隔

        *

        * @param str1

        * @param str2

        * @return

        */

      public static long twoTimeDiffMin(String str1, String str2) {

          DateFormat df =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Date one;

    Date two;

    long min =0;

    try {

            one = df.parse(str1);

    two = df.parse(str2);

    long time1 = one.getTime();

    long time2 = two.getTime();

    long diff;

    if (time1 < time2) {

                diff = time2 - time1;

    } else {

                diff = time1 - time2;

    }

            min = diff /(60 *1000);

    } catch (ParseException e) {

            e.printStackTrace();

    }

          return min;

    }

      /**

        *  num  为正数 往后多少天    负数  往前多少天

        *  dateType  时间格式

        */

      public static String getNewDay(int num,String dateType){

          if(StringUtils.isEmpty(dateType)){

            dateType=DateUtils.DATE_SMALL_STR;

    }

          Date date=new Date();//取时间

          Calendar calendar =new GregorianCalendar();

    calendar.setTime(date);

    calendar.add(Calendar.DATE,num);//把日期往后增加指定天.整数往后推,负数往前移动

          date=calendar.getTime();//这个时间就是日期往后推一天的结果

          SimpleDateFormat formatter =new SimpleDateFormat(dateType);

    String dateString = formatter.format(date);

    return dateString;

    }

      /**

        * 获取上N个月最后一天

        * @return

        */

      public static Date getLastDateByMonth(int n){

          Calendar calEnd = Calendar.getInstance();

    calEnd.setTime(new Date());

    calEnd.add(Calendar.MONTH, -(n-1));

    calEnd.set(Calendar.DAY_OF_MONTH,0);//设置为0号,本月的第0天就是上个月的最后一天

          return  calEnd.getTime();

    }

        /**

        * 获取上N个月第一天

        * @return

        */

      public static Date getFirstDateDay(int n) {

          Calendar calBegin = Calendar.getInstance();

    calBegin.setTime(new Date());

    calBegin.add(Calendar.MONTH, -n);

    calBegin.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天

            return  calBegin.getTime();

    }

      public static void main(String[] args) {

    //    DateUtils.format(DateUtils.getFirstDateDay(j),DateUtils.DATE_SMALL_STR)+" 00:00:01"

    //    DateUtils.format(DateUtils.getLastDateByMonth(j),DateUtils.DATE_SMALL_STR)+" 23:59:59"

          System.out.println(DateUtils.format(DateUtils.getFirstDateDay(1),DateUtils.DATE_SMALL_STR)+" 00:00:01");

    System.out.println(DateUtils.format(DateUtils.getLastDateByMonth(1),DateUtils.DATE_SMALL_STR)+" 23:59:59");

    }

    }

    相关文章

      网友评论

        本文标题:java时间工具类

        本文链接:https://www.haomeiwen.com/subject/jyiajktx.html