diff --git a/src/main/java/info/istlab/dp/dp2/DecoratorTest.java b/src/main/java/info/istlab/dp/dp2/DecoratorTest.java new file mode 100644 index 0000000..67ad0d3 --- /dev/null +++ b/src/main/java/info/istlab/dp/dp2/DecoratorTest.java @@ -0,0 +1,96 @@ +package info.istlab.dp.dp2; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; + +/** + * 誕生日:通常は西暦で管理しており、年齢などを出力するが、 + * 必要に応じて和暦で表示する。 + */ +public class DecoratorTest { + public static void main(String[] args) { + ArrayList chkDays = new ArrayList(); + chkDays.add(LocalDate.now()); + chkDays.add(LocalDate.of(2023, 5, 2)); + chkDays.add(LocalDate.of(2019, 5, 1)); + chkDays.add(LocalDate.of(2019, 4, 30)); + chkDays.add(LocalDate.of(1989, 1, 8)); + chkDays.add(LocalDate.of(1989, 1, 7)); + + for (LocalDate ld : chkDays) { + Wareki wareki = new Wareki(ld); + System.out.println(wareki.toString()); + System.out.println("-----"); + } + } +} + +/** + * LocalDate を装飾(Decorate)する和暦クラス + * つかいかたの例: + * Wareki wareki = new Wareki( LocalDate.now() ); + * System.out.println(wareki.toString()); + * + * または: System.out.println( Wareki.localDate2Wareki( LocalDate.now() ) ); + */ +class Wareki { + LocalDate ld; + + public Wareki(LocalDate _ld) { + ld = _ld; + } + + public String toString() { + return localDate2Wareki(ld); + } + + /** + * LocalDate から和暦を返す + * @param d LocalDate + * @return 和暦 + */ + public static String localDate2Wareki(LocalDate d) { + int month = d.getMonthValue(); + int day = d.getDayOfMonth(); + return String.format("%s/%02d/%02d", getNengo(d), month, day); + } + + /** + * 年号アルファベット+年 を返す + * + * @return 年号アルファベット+年 + */ + public static String getNengo(LocalDate localDate) { + String[] nengoArray = { "M", "T", "S", "H", "R" }; // Meiji,Taisho,Showa,Heisei,Reiwa + int[] fromYear = { 1868, 1912, 1926, 1989, 2019 }; + int[] fromMonth = { 1, 7, 12, 1, 5 }; + int[] fromDay = { 25, 30, 25, 8, 1 }; + + int year = localDate.getYear(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd"); + + String ymd = formatter.format(localDate); // 形式:YYYY/MM/DD (例: 1999/10/22) + String nengo = null; + int nengoYear = 0; + for (int i = nengoArray.length - 1; i > 0; i--) { + String fromYMD = new BirthDay(fromYear[i], fromMonth[i], fromDay[i]).toString(); + // System.out.print(" >> check "+fromYMD+" <= "+ymd); + if (fromYMD.compareTo(ymd) <= 0) { // YYYY/MM/DD文字列の大小関係でチェックしている + // System.out.println(" OK"); + nengo = nengoArray[i]; + nengoYear = year - fromYear[i] + 1; + break; + } else { + // System.out.println(" X"); + } + } + if (nengo == null) { + nengo = "E"; + nengoYear = year - 1603 + 1; + } + return String.format("%s%02d", nengo, nengoYear); // ex. R05 H30 + } + +} +