Various classes are prepared for the date and time type of java8. Although it is multifunctional, it is difficult to use (Japanese calendar can be handled with Japanese Date, but it does not have time information, etc.), so I thought of a utility method that outputs an arbitrary date and time in an arbitrary format.
DateTimeFormat.java
import java.time.LocalTime;
import java.time.chrono.ChronoLocalDateTime;
import java.time.chrono.JapaneseDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.util.Locale;
import java.util.function.Function;
@SuppressWarnings("javadoc")
public class DateTimeFormat {
public static String dateTimeFormat(String format) {
return dateTimeFormat(format, Function.identity());
}
public static String dateTimeFormat(String format, Function<ChronoLocalDateTime<JapaneseDate>, ChronoLocalDateTime<JapaneseDate>> modify) {
return modify.apply(JapaneseDate.now().atTime(LocalTime.now())).format(DateTimeFormatter.ofPattern(format, Locale.JAPAN));
}
public static void main(String[] __) {
//Current date and time
System.out.println(dateTimeFormat("uuuu/MM/dd(E) HH:mm:ss"));
System.out.println(dateTimeFormat("Gy year M month d day(EEEE)H hours m minutes s seconds"));
System.out.println(dateTimeFormat("GGGGGy.M.d"));
//Last day of this month
System.out.println(dateTimeFormat("uuuu/MM/dd(E)", d -> d.with(ChronoField.DAY_OF_MONTH, d.toLocalDate().lengthOfMonth())));
//After a week
System.out.println(dateTimeFormat("Gy year M month d day(E)", d -> d.plus(7, ChronoUnit.DAYS)));
//1st next month
System.out.println(dateTimeFormat("GGGGGy.M.d", d -> d.with(ChronoField.DAY_OF_MONTH, 1).plus(1, ChronoUnit.MONTHS)));
}
}
Execution result
2017/06/15(wood) 11:30:05
June 15, 2017(Thursday)11:30:05
H29.6.15
2017/06/30(Money)
June 22, 2017(wood)
H29.7.1
Recommended Posts