詳解JAVA常用的時間操作【實用】_java

來源:互聯網
上載者:User

項目中經常有對時間進行處理的需求,下面是一些常用的操作整理,方便以後再次使用以及做相關複習。

1.字串轉換為日期

/**   * 字串轉換為日期   * @param dateStr 需要轉換的日期   * @param dateFormat 日期格式yyyy-MM-dd/yyyy-MM-dd HH:mm:ss   */  public static Date toDate(String dateStr, SimpleDateFormat dateFormat) throws ParseException{    Date date = null;    try {      date = dateFormat.parse(dateStr);    } catch (ParseException e) {      logger.debug("Fail to convert String to Date, {}", dateStr);    }    return date;  }

2.時間戳記轉日期

/**   * 時間戳記轉日期   * @param date   * @return   */  public static String dateToTime(long time, SimpleDateFormat dateFormat) throws ParseException{     String data = null;     try {       dateFormat.format(new Date(time*1000));       } catch (Exception e) {       logger.debug("Fail to convert long to Date, {}", time);     }     return data;  }

3.日期格式化成字串

/**   * 日期格式化成字串   * @param date   * @param dateFormat   * @return   * @throws ParseException   */  public static String toString(Date date, SimpleDateFormat dateFormat) throws ParseException{    return dateFormat.format(date);  }

4.擷取指定日期之前或之後的日期 ,十分秒為00:00:00

 /**   * 擷取指定日期之前或之後的日期   * @param date    * @param num 正數為之後,負數為之前   * @return yyyy-MM-dd 00:00:00   */  public static Date getSpecificDate(Date date, int num){    Calendar todayCal = Calendar.getInstance();    todayCal.setTime(date);    Calendar c = Calendar.getInstance();    c.set(todayCal.get(Calendar.YEAR), todayCal.get(Calendar.MONTH), todayCal.get(Calendar.DAY_OF_MONTH) + num, 0, 0, 0);    return c.getTime();  }

5.擷取指定日期之前或之後的日期 ,時分秒為當前的

  /**   * 擷取指定日期之前或之後的日期   * @param date    * @param num 正數為之前,負數為之後   * @return yyyy-MM-dd + 當前的時分秒   */  public static Date getSpecificDateAndHhMmSs(Date date,int num){    Calendar c = Calendar.getInstance();     c.setTime(date);     int day=c.get(Calendar.DATE);     c.set(Calendar.DATE,day - num);     return c.getTime();   }

6.將time類型的時間字串 轉換成 時、分

  /**   * 將time類型的時間字串 轉換成 時、分   * HH-mm-ss -->> HH-mm   * @param time    * @return   */  public static String timeToHHMM(String time){    return time.substring(0, time.length() - 3);  }

7.擷取某個日期的時、分

  /**   * 擷取某個日期的時、分   * @param date   * @return HH-mm   */  public static String getHM(Date date){    Calendar ca = Calendar.getInstance();     ca.setTime(date);    Integer hour = ca.get(Calendar.HOUR_OF_DAY);//小時     Integer minute = ca.get(Calendar.MINUTE);//分    String rs_hour = hour.toString();    String rs_minute = minute.toString();    if (rs_hour.length() == 1){      rs_hour = "0" + hour;    }    if(rs_minute.length() == 1){      rs_minute = "0" + minute;    }    return rs_hour + ":" + rs_minute;  }

8.time類型的時間字串 -->> 零點開始的秒數

  /**   * time類型的時間字串 -->> 零點開始的秒數   * @param time HH-mm / HH-mm-ss   * @return   */  public static Integer timeToSeconds(String time){     String[] timeSplit = null;     int hours = 0,minutes = 0,seconds = 0;     try {       timeSplit = time.split(":");       if (timeSplit.length == 2) {         hours = Integer.valueOf(timeSplit[0])*60*60;         minutes = Integer.valueOf(timeSplit[1])*60;       }else if(timeSplit.length == 3){         hours = Integer.valueOf(timeSplit[0])*60*60;         minutes = Integer.valueOf(timeSplit[1])*60;         seconds = Integer.valueOf(timeSplit[2]);       }else{         logger.debug("Fail to convert the time, {}", time);       }     } catch (Exception e) {       logger.debug("Fail to convert the time, {}", time);       throw e;     }    return hours + minutes + seconds;  }

9.零點開始的秒數轉時間 -->> HH-mm-ss

  /**   * 零點開始的秒數轉時間 -->> HH-mm-ss   * @param durationSeconds   * @return   */  public static String getDuration(int durationSeconds){     int hours = durationSeconds /(60*60);     int leftSeconds = durationSeconds % (60*60);     int minutes = leftSeconds / 60;     int seconds = leftSeconds % 60;     StringBuffer sBuffer = new StringBuffer();     sBuffer.append(addZeroPrefix(hours));     sBuffer.append(":");     sBuffer.append(addZeroPrefix(minutes));     sBuffer.append(":");     sBuffer.append(addZeroPrefix(seconds));     return sBuffer.toString();   }   public static String addZeroPrefix(int number){     if(number < 10)       return "0"+number;     else       return ""+number;   }

10.比較兩個日期相差的秒數

  /**   * 比較兩個日期相差的秒數   * @param startDate   * @param endDate   * @return   */  public static int getTimeSeconds(Date startDate,Date endDate) {     long a = endDate.getTime();     long b = startDate.getTime();     return (int)((a - b) / 1000);  }

11.判斷兩個時間段是否存在交集

  /**   * 比較兩個日期相差的秒數   * @param startDate   * @param endDate   * @return   */  public static int getTimeSeconds(Date startDate,Date endDate) {     long a = endDate.getTime();     long b = startDate.getTime();     return (int)((a - b) / 1000);  }

12.擷取指定日期是星期幾(1-7分別代表周一至周日)

  /**   * 擷取指定日期是星期幾(1-7分別代表周一至周日)   * @return   */  public static int DayOfWeek(Date date){    Calendar now = Calendar.getInstance();    now.setTime(date);    boolean isFirstDay = (now.getFirstDayOfWeek() == Calendar.SUNDAY);    int weekday = now.get(Calendar.DAY_OF_WEEK);    if(isFirstDay){      weekday = weekday - 1;      if(weekday == 0){        weekday = 7;      }    }    return weekday;  }

以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的協助,同時也希望多多支援雲棲社區!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.