diff --git a/calendar.rb b/calendar.rb new file mode 100644 index 0000000..3f4cf37 --- /dev/null +++ b/calendar.rb @@ -0,0 +1,19 @@ +#encoding: utf-8 +module Calendar + def self.convert(date) + return nil unless date + year, month, day = date.split('-').map(&:to_i) + if Date.parse(date) >= Date.parse("1989-01-08") + japanese_year = "平成#{(year - 1989 + 1).to_s.rjust(2, '0')}" + elsif Date.parse(date) >= Date.parse("1926-12-25") + japanese_year = "昭和#{(year - 1926 + 1).to_s.rjust(2, '0')}" + elsif Date.parse(date) >= Date.parse("1912-07-30") + japanese_year = "大正#{(year - 1912 + 1).to_s.rjust(2, '0')}" + elsif Date.parse(date) >= Date.parse("1868-09-08") + japanese_year = "明治#{(year - 1868 + 1).to_s.rjust(2, '0')}" + else + raise ArgumentError, "Dates earlier than the Meiji era are unsupported" + end + "#{japanese_year}年#{month.to_s.rjust(2, '0')}月#{day.to_s.rjust(2, '0')}日" + end +end \ No newline at end of file diff --git a/calendar_spec.rb b/calendar_spec.rb new file mode 100644 index 0000000..ec493b7 --- /dev/null +++ b/calendar_spec.rb @@ -0,0 +1,38 @@ +# encoding: utf-8 + +require 'rubygems' +require 'rspec' +require "#{File.dirname(__FILE__)}/calendar" + +describe Calendar do + it "should return a blank string for nil input" do + Calendar.convert(nil).should == nil + end + + it "should work for today" do + Calendar.convert("2012-10-20").should == "平成24年10月20日" + end + + it "should work for border of era" do + Calendar.convert("1989-01-07").should == "昭和64年01月07日" + Calendar.convert("1989-01-08").should == "平成01年01月08日" + Calendar.convert("1989-01-09").should == "平成01年01月09日" + end + + it "should work for Showa dates (natsukashii)" do + Calendar.convert("1979-08-08").should == "昭和54年08月08日" + end + + it "should work for Taisho dates (furui)" do + Calendar.convert("1912-07-30").should == "大正01年07月30日" + end + + it "should work for Meiji dates (motto furui)" do + Calendar.convert("1868-09-08").should == "明治01年09月08日" + end + + it "should throw error for pre-Meiji dates" do + expect{Calendar.convert("1868-09-01")}.to raise_error(ArgumentError) + end +end +