Java String與時間相互轉換

String時間互轉

兩種辦法:

  1. 使用DateFormat
  2. 使用DateTimeFormatter

一、DateFormat

  1. String轉時間

    DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
    DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String s ="2020-05-09";
    String S2= "2020-05-10 16:21:02 ";
    Date date = format1.parse(s);
    Date date2 = format2.parse(S2);
    System.out.println("date="+date);
    System.out.println("date2="+date2);
    
    結果:
    date=Sat May 09 00:00:00 CST 2020
    date2=Sun May 10 16:21:02 CST 2020
    
  2. 時間轉String

    Date datex = new Date();
    DateFormat format3 = new SimpleDateFormat("yyyy-MM-dd");
    DateFormat format4 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    System.out.println("format3="+format3.format(datex));
    System.out.println("format4="+format4.format(datex));
    
    結果:
    format3=2020-05-13
    format4=2020-05-13 13:39:59
    

二、DateTimeFormatter

     // String --> LocalDate
     LocalDate localDate1 = LocalDate.parse("2020-12-07");
     DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
     System.out.println(LocalDate.parse("2019-10-09").format(pattern));
     // String --> LocalTime
     LocalTime localTime = LocalTime.parse("07:43:53");
     // String -->LocalDateTime
     DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
     LocalDateTime localDate = LocalDateTime.parse("2019-12-07 07:43:53",formatter1);
             
     System.out.println("localDate"+localDate);
     System.out.println("localTime"+localTime);
     System.out.println("localDate"+localDate);


------------------
localDate 2019-12-07T07:43:53
localTime 07:43:53
localDate 2019-12-07T07:43:53
    

設置時區

TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章