Open1

Rubyで西暦と和暦変換をする

1AR1M1AR1M

AIに書いてもらいました。

require 'date'

class JapaneseEra
  ERA_DATA = [
    { name: '令和', start_date: Date.new(2019, 5, 1) },
    { name: '平成', start_date: Date.new(1989, 1, 8) },
    { name: '昭和', start_date: Date.new(1926, 12, 25) },
    { name: '大正', start_date: Date.new(1912, 7, 30) },
    { name: '明治', start_date: Date.new(1868, 1, 25) }
  ].freeze

  def self.to_japanese(date, format = :full)
    era = ERA_DATA.find { |era| date >= era[:start_date] }
    
    if era
      year = date.year - era[:start_date].year + 1
      year_string = year == 1 ? '元' : year.to_s
      
      case format
      when :era
        era[:name]
      when :year
        year_string
      when :month
        date.month.to_s
      when :day
        date.day.to_s
      when :era_year
        "#{era[:name]}#{year_string}"
      when :full
        "#{era[:name]}#{year_string}#{date.month}#{date.day}日"
      else
        raise ArgumentError, "Unknown format: #{format}"
      end
    else
      case format
      when :era
        ''
      when :year
        date.year.to_s
      when :month
        date.month.to_s
      when :day
        date.day.to_s
      when :era_year, :full
        "#{date.year}#{date.month}#{date.day}日"
      else
        raise ArgumentError, "Unknown format: #{format}"
      end
    end
  end

  def self.to_western(era, year, month = 1, day = 1)
    era_data = ERA_DATA.find { |data| data[:name] == era }
    raise ArgumentError, "Unknown era: #{era}" unless era_data

    year = 1 if year == '元'
    year = year.to_i

    western_year = era_data[:start_date].year + year - 1
    Date.new(western_year, month.to_i, day.to_i)
  rescue Date::Error
    raise ArgumentError, "Invalid date"
  end
end