「Java8」DateTimeFormatterクラスでLocalDate日付をフォーマットするサンプル
説明
format(DateTimeFormatter formatter)
指定されたフォーマッタを使用してこの時間を書式設定します。
Javaコード
package com.arkgame.study.utils;
import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
public class LocalDateFmtDemo {
public static final String datePattern = "yyyy/MM/dd";
public static void main(String[] args) {
// year month dayOfMonth
LocalDate localDateA = LocalDate.of(2020, 10, 27);
// year Month dayofMonth
LocalDate localDateB = LocalDate.of(2020, Month.NOVEMBER, 14);
// year dayOfMonth
LocalDate localDateC = LocalDate.ofYearDay(2020, 120);
String resA = fmtFunc(localDateA);
String resB = fmtFunc(localDateB);
String resC = fmtFunc(localDateC);
System.out.println("日付Aフォーマット結果: " + resA);
System.out.println("日付Bフォーマット結果: " + resB);
System.out.println("日付Cフォーマット結果: " + resC);
}
public static String fmtFunc(LocalDate localDate) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(datePattern);
String fmtResult;
fmtResult = localDate.format(fmt);
return fmtResult;
}
}
package com.arkgame.study.utils;
import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
public class LocalDateFmtDemo {
public static final String datePattern = "yyyy/MM/dd";
public static void main(String[] args) {
// year month dayOfMonth
LocalDate localDateA = LocalDate.of(2020, 10, 27);
// year Month dayofMonth
LocalDate localDateB = LocalDate.of(2020, Month.NOVEMBER, 14);
// year dayOfMonth
LocalDate localDateC = LocalDate.ofYearDay(2020, 120);
String resA = fmtFunc(localDateA);
String resB = fmtFunc(localDateB);
String resC = fmtFunc(localDateC);
System.out.println("日付Aフォーマット結果: " + resA);
System.out.println("日付Bフォーマット結果: " + resB);
System.out.println("日付Cフォーマット結果: " + resC);
}
public static String fmtFunc(LocalDate localDate) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(datePattern);
String fmtResult;
fmtResult = localDate.format(fmt);
return fmtResult;
}
}
package com.arkgame.study.utils; import java.time.LocalDate; import java.time.Month; import java.time.format.DateTimeFormatter; public class LocalDateFmtDemo { public static final String datePattern = "yyyy/MM/dd"; public static void main(String[] args) { // year month dayOfMonth LocalDate localDateA = LocalDate.of(2020, 10, 27); // year Month dayofMonth LocalDate localDateB = LocalDate.of(2020, Month.NOVEMBER, 14); // year dayOfMonth LocalDate localDateC = LocalDate.ofYearDay(2020, 120); String resA = fmtFunc(localDateA); String resB = fmtFunc(localDateB); String resC = fmtFunc(localDateC); System.out.println("日付Aフォーマット結果: " + resA); System.out.println("日付Bフォーマット結果: " + resB); System.out.println("日付Cフォーマット結果: " + resC); } public static String fmtFunc(LocalDate localDate) { DateTimeFormatter fmt = DateTimeFormatter.ofPattern(datePattern); String fmtResult; fmtResult = localDate.format(fmt); return fmtResult; } }
結果
日付Aフォーマット結果: 2020/10/27
日付Bフォーマット結果: 2020/11/14
日付Cフォーマット結果: 2020/04/29