Java將字符串轉化爲時間格式,與實現日期的計算


將字符串轉化爲時間格式,具體如下:


有這樣一個字符串:“20070911121547”, 
轉換成時間格式:2007-09-11 12:15:47 

java代碼:

  1. public class bb {  
  2.     public static void main(String[] args) {  
  3.         // TODO Auto-generated method stub      
  4.         SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");  

  5.         String dateString = "20071128175545";  
  6.         try {  
  7.             Date date = df.parse(dateString);  
  8.             System.out.println(df.format(date));  
  9.         } catch (Exception ex) {  
  10.             System.out.println(ex.getMessage());  
  11.         }  
  12.     }  
  13.   
  14. }  


------------------------------------------------------------------------------------------------------

使用jdk 8 的時間API實現創建新的自定義時間,並此基礎上計算,增加(天,月,年),具體見JDK 8時間的使用文章。

java代碼:

try { 
      Integer yeah = 2016;
      Integer moon = 8;
      Integer day =15;
      LocalDate dateOfBirth = LocalDate.of(yeah, moon, day);
      LocalDate ldt = dateOfBirth.plusDays(8); 
      System.out.println(ldt);
    } catch (Exception ex) {  
        System.out.println(ex.getMessage());  
    }  



根據上述例子,可以放在一個循環中,實現對兩個日期之間所有日期的遍歷



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章