「Java8」DateTimeFormatter.ofPattern()で日付パターンを指定するサンプル

2020年11月13日

説明
1.public String format(DateTimeFormatter formatter)
指定されたフォーマッタを使用してこの日付/時間を書式設定します。
2.public static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter)
特定のフォーマッタを使用して、テキスト文字列からLocalDateTimeのインスタンスを取得します。
Javaコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study.it;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class SimpleDateLocalTime {
// DateTimeFormatter
private static final DateTimeFormatter dateFmt = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
// main method
public static void main(String[] args) throws ParseException {
String strA = "2020/10/13 10:21:34";
// strLdtメソッドを呼び出す
LocalDateTime localDateTime = strLdt(strA);
System.out.println("String->DateTimeFormatter作成: " + localDateTime.format(dateFmt));
}
// String -> LocalDateTime
public static LocalDateTime strLdt(String target) {
LocalDateTime ldt = LocalDateTime.parse(target, dateFmt);
return ldt;
}
}
package com.arkgame.study.it; import java.text.ParseException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class SimpleDateLocalTime { // DateTimeFormatter private static final DateTimeFormatter dateFmt = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); // main method public static void main(String[] args) throws ParseException { String strA = "2020/10/13 10:21:34"; // strLdtメソッドを呼び出す LocalDateTime localDateTime = strLdt(strA); System.out.println("String->DateTimeFormatter作成: " + localDateTime.format(dateFmt)); } // String -> LocalDateTime public static LocalDateTime strLdt(String target) { LocalDateTime ldt = LocalDateTime.parse(target, dateFmt); return ldt; } }
package com.arkgame.study.it;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class SimpleDateLocalTime {

      // DateTimeFormatter
      private static final DateTimeFormatter dateFmt = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");

      // main method
      public static void main(String[] args) throws ParseException {
            String strA = "2020/10/13 10:21:34";
            // strLdtメソッドを呼び出す
            LocalDateTime localDateTime = strLdt(strA);
            System.out.println("String->DateTimeFormatter作成: " + localDateTime.format(dateFmt));
      }

      // String -> LocalDateTime
      public static LocalDateTime strLdt(String target) {
            LocalDateTime ldt = LocalDateTime.parse(target, dateFmt);
            return ldt;
      }

}

結果
String->DateTimeFormatter作成: 2020/10/13 10:21:34

Java

Posted by arkgame