「Java」DateTimeFormatterクラスとLocalDateTimeクラスを使用するサンプル

説明
public static DateTimeFormatter ofPattern(String pattern)
指定されたパターンを使用してフォーマッタを作成します。
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study.tm;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeeFormatterDemo {
private static final String ptn = "yyyy/MM/dd HH:mm:ss.SSS";
public static void main(String[] args) throws ParseException {
String target = "2021/03/05 14:05:56.123";
funcA(target);
}
public static void funcA(String target) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(ptn);
LocalDateTime ldt = LocalDateTime.parse(target, dtf);
System.out.println("結果1:\n" + ldt);
String result = dtf.format(ldt);
System.out.println("結果2:\n" + result);
}
}
package com.arkgame.study.tm; import java.text.ParseException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DateTimeeFormatterDemo { private static final String ptn = "yyyy/MM/dd HH:mm:ss.SSS"; public static void main(String[] args) throws ParseException { String target = "2021/03/05 14:05:56.123"; funcA(target); } public static void funcA(String target) { DateTimeFormatter dtf = DateTimeFormatter.ofPattern(ptn); LocalDateTime ldt = LocalDateTime.parse(target, dtf); System.out.println("結果1:\n" + ldt); String result = dtf.format(ldt); System.out.println("結果2:\n" + result); } }
package com.arkgame.study.tm;

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

public class DateTimeeFormatterDemo {

      private static final String ptn = "yyyy/MM/dd HH:mm:ss.SSS";

      public static void main(String[] args) throws ParseException {
            String target = "2021/03/05 14:05:56.123";
            funcA(target);
      }

      public static void funcA(String target) {
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern(ptn);
            LocalDateTime ldt = LocalDateTime.parse(target, dtf);

            System.out.println("結果1:\n" + ldt);

            String result = dtf.format(ldt);
            System.out.println("結果2:\n" + result);
      }
}

実行結果
結果1:
2021-03-05T14:05:56.123
結果2:
2021/03/05 14:05:56.123

Java

Posted by arkgame