0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Java 西暦和暦変換方法

Posted at

ポイント
①西暦→和暦の場合は和暦配列を作成する
和暦配列はString型の二次元配列
和暦テーブルには各元号ごとに開始年月日、終了年月日、年号の記載を格納する
②Calenderクラスを使用する

warekiHenkan.Java
public static void main(String[] args) {

    	Scanner sc = new Scanner(System.in);
        String line = sc.nextLine();
        
        String[] seirekiList = line.split(" ");
        String month = String.format("%02d", Integer.parseInt(seirekiList[1]));
        String date = String.format("%02d", Integer.parseInt(seirekiList[2]));
        
        String seireki = seirekiList[0] + month + date;
        
      //和暦変換テーブル
        String warekiTable[][] = {
            {"18680908","19120729", "明治"},   //明治          
            {"19120730","19261224", "大正"},   //大正
            {"19261225","19890107", "昭和"},   //昭和
            {"19890108","20190430", "平成"},   //平成
            {"20190501","30001231", "令和"},   //令和
        };
        int year = Integer.parseInt(seirekiList[0]);
        
        //暦変換テーブルをサーチする
        int i = 0;
        for (i=0; i<warekiTable.length; i++) {
            //当該西暦が開始年以上で最終年以下ならbreak
            if (seireki.compareTo(warekiTable[i][0]) >= 0 && seireki.compareTo(warekiTable[i][1]) <= 0) {
                break;
            }
        }
        //暦テーブルに該当レコードがあれば、和暦年を計算する
        if (i < warekiTable.length) {
            int jpYear = year - Integer.parseInt(warekiTable[i][0].substring(0,4)) + 1;
            String year1 = String.valueOf(jpYear);
            //和号+和暦年を返す
            if(year1.equals("1")) {
            	year1 = "元";
            }
            System.out.println(warekiTable[i][2] + year1 + "年" + seirekiList[1] + "月" + seirekiList[2] + "日");
        }
    }
0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?