Skip to main content
Contents

Implementation · Ruby

Persian (Jalali) calendar in Ruby

Dependency-free Ruby implementation of the Jalali (Persian, Solar Hijri) calendar: leap years, date validation, Gregorian and Julian Day conversion, weekday and day of year. Verified day by day for 1178–3000 AP. MIT license.

Requires
Ruby 3+
Tested with
Ruby 4.0
Cross-checked against
ICU4C 76.1–79.1 (Fiddle)
Language-specific checks
TypeError for Float/String, frozen tables, Bignum inputs
License
MIT
Version
1.0.0

Quick start

  1. Copy or download the source file into your project (no dependencies).

  2. Optionally, run its tests. The .zip keeps the folder layout they expect; from the language folder:

    implementations/ruby
    ruby test_persian_calendar.rb
  3. Call the shared API: function reference

Source

persian_calendar.rb

· 158 lines
Download
# Copyright (C) 2026 Goudarz Jafari <hi@goudarzjafari.com>
# SPDX-License-Identifier: MIT

# frozen_string_literal: true

# Solar Hijri (Persian, Jalali, Shamsi) calendar.
#
# Algorithm: 33-year arithmetic rule + 78-year correction table,
# the same algorithm as ICU 77.1+ and ICU4X. Matches the astronomical calendar (52.5 E meridian)
# for 1178-3000 AP. Months are 1-based; weekdays 0 = Saturday ... 6 = Friday.
#
# Inputs outside MIN_YEAR..MAX_YEAR / MIN_JDN..MAX_JDN raise RangeError; non-Integers
# raise TypeError; invalid dates raise ArgumentError.
#
# Ruby's Integer#/ and #% already use floor semantics, which the formulas need.

require 'date'
require 'set'

module PersianCalendar
  PersianDate = Struct.new(:year, :month, :day)

  # Years checked against the astronomical calendar.
  VERIFIED_MIN_YEAR = 1178
  VERIFIED_MAX_YEAR = 3000

  # Accepted input range.
  MIN_YEAR = -100_000
  MAX_YEAR = 100_000
  MIN_JDN = -34_576_287 # 1 Farvardin -100000 (Gregorian -99379-03-29)
  MAX_JDN = 38_472_562  # 29 Esfand 100000 (Gregorian 100622-03-13)

  EPOCH_JDN = 1_948_320
  private_constant :EPOCH_JDN

  # Years the 33-year rule calls leap but are not; the next year is leap instead.
  NON_LEAP_CORRECTION = Set[
    1502, 1601, 1634, 1667, 1700, 1733, 1766, 1799, 1832, 1865, 1898, 1931,
    1964, 1997, 2030, 2059, 2063, 2096, 2129, 2158, 2162, 2191, 2195, 2224,
    2228, 2257, 2261, 2290, 2294, 2323, 2327, 2356, 2360, 2389, 2393, 2422,
    2426, 2455, 2459, 2488, 2492, 2521, 2525, 2554, 2558, 2587, 2591, 2620,
    2624, 2653, 2657, 2686, 2690, 2719, 2723, 2748, 2752, 2756, 2781, 2785,
    2789, 2818, 2822, 2847, 2851, 2855, 2880, 2884, 2888, 2913, 2917, 2921,
    2946, 2950, 2954, 2979, 2983, 2987
  ].freeze

  MONTH_NAMES_FA = %w[فروردین اردیبهشت خرداد تیر مرداد شهریور مهر آبان آذر دی بهمن اسفند].freeze
  MONTH_NAMES_EN = %w[Farvardin Ordibehesht Khordad Tir Mordad Shahrivar Mehr Aban Azar Dey Bahman Esfand].freeze
  WEEKDAY_NAMES_FA = ['شنبه', 'یکشنبه', 'دوشنبه', "سه‌شنبه", 'چهارشنبه', 'پنجشنبه', 'جمعه'].freeze
  WEEKDAY_NAMES_EN = %w[Saturday Sunday Monday Tuesday Wednesday Thursday Friday].freeze

  module_function

  def check_int(name, value)
    raise TypeError, "#{name} must be an Integer, not #{value.class}" unless value.is_a?(Integer)
  end
  private_class_method :check_int

  def check_year(year)
    check_int('year', year)
    raise RangeError, "year out of range [#{MIN_YEAR}, #{MAX_YEAR}]: #{year}" unless (MIN_YEAR..MAX_YEAR).cover?(year)
  end
  private_class_method :check_year

  def check_jdn(jdn)
    check_int('jdn', jdn)
    raise RangeError, "jdn out of range [#{MIN_JDN}, #{MAX_JDN}]: #{jdn}" unless (MIN_JDN..MAX_JDN).cover?(jdn)
  end
  private_class_method :check_jdn

  def leap_year?(year)
    check_year(year)
    return false if NON_LEAP_CORRECTION.include?(year)
    return true if NON_LEAP_CORRECTION.include?(year - 1)

    (25 * year + 11) % 33 < 8
  end

  def days_in_month(year, month)
    check_year(year)
    check_int('month', month)
    raise ArgumentError, "month out of range: #{month}" unless (1..12).cover?(month)
    return 31 if month <= 6
    return 30 if month <= 11

    leap_year?(year) ? 30 : 29
  end

  # True for a real Persian date in the accepted range; never raises.
  def valid_date?(year, month, day)
    return false unless [year, month, day].all?(Integer)

    (MIN_YEAR..MAX_YEAR).cover?(year) && (1..12).cover?(month) && day >= 1 && day <= days_in_month(year, month)
  end

  def nowruz_jdn(year)
    jdn = EPOCH_JDN + 365 * (year - 1) + (8 * year + 21) / 33
    NON_LEAP_CORRECTION.include?(year - 1) ? jdn - 1 : jdn
  end
  private_class_method :nowruz_jdn

  def days_before_month(month)
    month <= 7 ? 31 * (month - 1) : 30 * (month - 1) + 6
  end
  private_class_method :days_before_month

  # Julian Day Number of a Persian date.
  def check_date(year, month, day)
    return if valid_date?(year, month, day)

    check_int('year', year)
    check_int('month', month)
    check_int('day', day)
    raise ArgumentError, "invalid Persian date: #{year}/#{month}/#{day}"
  end
  private_class_method :check_date

  def to_jdn(year, month, day)
    check_date(year, month, day)

    nowruz_jdn(year) + days_before_month(month) + day - 1
  end

  def from_jdn(jdn)
    check_jdn(jdn)
    year = 1 + (33 * (jdn - EPOCH_JDN) + 3) / 12_053
    year += 1 while jdn >= nowruz_jdn(year + 1)
    year -= 1 while jdn < nowruz_jdn(year)
    doy = jdn - nowruz_jdn(year) # 0-based
    return PersianDate.new(year, doy / 31 + 1, doy % 31 + 1) if doy < 186

    doy -= 186
    PersianDate.new(year, doy / 30 + 7, doy % 30 + 1)
  end

  # Date#jd is the Julian Day Number; Date::GREGORIAN makes the date proleptic Gregorian.
  def from_date(date)
    raise TypeError, "expected a Date, not #{date.class}" unless date.is_a?(Date)

    from_jdn(date.jd)
  end

  def to_date(year, month, day)
    Date.jd(to_jdn(year, month, day), Date::GREGORIAN)
  end

  # 0 = Saturday (شنبه) ... 6 = Friday (جمعه).
  def day_of_week(year, month, day)
    (to_jdn(year, month, day) + 2) % 7
  end

  # 1 ... 365/366.
  def day_of_year(year, month, day)
    check_date(year, month, day)

    days_before_month(month) + day
  end
end

Tests

test_persian_calendar.rb

152 lines
RubyDownload
# Copyright (C) 2026 Goudarz Jafari <hi@goudarzjafari.com>
# SPDX-License-Identifier: MIT

# frozen_string_literal: true

# Checks persian_calendar.rb against /data. Run: ruby implementations/ruby/test_persian_calendar.rb
require 'minitest/autorun'
require_relative 'persian_calendar'

class TestPersianCalendar < Minitest::Test
  PC = PersianCalendar
  DATA = File.expand_path('../../data', __dir__)

  def csv(name)
    File.readlines(File.join(DATA, name), chomp: true).drop(1).reject(&:empty?).map { |l| l.split(',') }
  end

  def test_years
    csv('years.csv').each do |r|
      y = r[0].to_i
      leap = r[1] == '1'
      assert_equal leap, PC.leap_year?(y), "leap #{y}"
      assert_equal leap ? 30 : 29, PC.days_in_month(y, 12)
      assert_equal Date.iso8601(r[3]), PC.to_date(y, 1, 1)
      assert_equal r[4].to_i, PC.to_jdn(y, 1, 1)
      assert_equal r[5].to_i, PC.day_of_week(y, 1, 1)
      # every day of the year against the ground truth, both directions
      r[2].to_i.times do |doy|
        m, d = doy < 186 ? [doy / 31 + 1, doy % 31 + 1] : [(doy - 186) / 30 + 7, (doy - 186) % 30 + 1]
        jdn = r[4].to_i + doy
        raise "#{y}/#{m}/#{d}" unless PC.from_jdn(jdn) == PC::PersianDate.new(y, m, d) && PC.to_jdn(y, m, d) == jdn
      end
    end
  end

  def test_vectors
    csv('test-vectors.csv').each do |r|
      jy, jm, jd, gy, gm, gd, jdn, wd = r.map(&:to_i)
      p = PC::PersianDate.new(jy, jm, jd)
      g = Date.new(gy, gm, gd, Date::GREGORIAN)
      assert_equal g, PC.to_date(jy, jm, jd)
      assert_equal p, PC.from_date(g)
      assert_equal jdn, PC.to_jdn(jy, jm, jd)
      assert_equal p, PC.from_jdn(jdn)
      assert_equal wd, PC.day_of_week(jy, jm, jd)
    end
  end

  def test_every_day_round_trips
    first = PC.to_jdn(PC::VERIFIED_MIN_YEAR, 1, 1)
    last = PC.to_jdn(PC::VERIFIED_MAX_YEAR, 12, PC.days_in_month(PC::VERIFIED_MAX_YEAR, 12))
    prev = PC.from_jdn(first - 1)
    (first..last).each do |jdn|
      d = PC.from_jdn(jdn)
      raise "round trip #{jdn}" unless PC.to_jdn(d.year, d.month, d.day) == jdn

      consecutive = (d.day == prev.day + 1 && d.month == prev.month && d.year == prev.year) ||
                    (d.day == 1 && ((d.month == prev.month + 1 && d.year == prev.year) ||
                                    (d.month == 1 && prev.month == 12 && d.year == prev.year + 1)))
      raise "not consecutive at #{jdn}" unless consecutive

      prev = d
    end
  end

  # Extrapolated years: years <= 0 make intermediate values negative (floor division matters).
  def test_extrapolated_years
    assert_equal 1_582_713, PC.to_jdn(-1000, 1, 1)
    assert_equal 1_947_955, PC.to_jdn(0, 1, 1)
    assert_equal 3_408_925, PC.to_jdn(4000, 1, 1)
    assert_equal PC::PersianDate.new(-5334, 9, 3), PC.from_jdn(0)
    assert_equal 1, PC.day_of_week(-1000, 1, 1)
    assert PC.leap_year?(-3)
    refute PC.leap_year?(-1000)
    [[-1000, 1177], [3001, 4000]].each do |first_year, last_year|
      first = PC.to_jdn(first_year, 1, 1)
      last = PC.to_jdn(last_year, 12, PC.days_in_month(last_year, 12))
      prev = PC.from_jdn(first - 1)
      (first..last).each do |jdn|
        d = PC.from_jdn(jdn)
        raise "round trip #{jdn}" unless PC.to_jdn(d.year, d.month, d.day) == jdn

        consecutive = (d.day == prev.day + 1 && d.month == prev.month && d.year == prev.year) ||
                      (d.day == 1 && ((d.month == prev.month + 1 && d.year == prev.year) ||
                                      (d.month == 1 && prev.month == 12 && d.year == prev.year + 1)))
        raise "not consecutive at #{jdn}" unless consecutive

        prev = d
      end
    end
  end

  def test_validation_and_known_dates
    assert PC.valid_date?(1403, 12, 30)
    refute PC.valid_date?(1404, 12, 30)
    assert PC.valid_date?(1404, 6, 31)
    refute PC.valid_date?(1404, 7, 31)
    refute PC.valid_date?(1404, 13, 1)
    refute PC.valid_date?(1404, 0, 1)
    refute PC.valid_date?(1404, 1, 0)
    assert_raises(ArgumentError) { PC.to_jdn(1404, 12, 30) }
    refute PC.valid_date?(1404, 1.5, 1) # not an integer
    assert_equal PC::PersianDate.new(1404, 1, 1), PC.from_date(Date.new(2025, 3, 21))
    assert_equal PC::PersianDate.new(1357, 11, 22), PC.from_date(Date.new(1979, 2, 11))
    assert_equal 187, PC.day_of_year(1404, 7, 1)
    assert_equal 'Friday', PC::WEEKDAY_NAMES_EN[PC.day_of_week(1404, 1, 1)]
  end

  # Limits: exact boundaries; everything outside raises (no huge Bignum loops, no Float results).
  def test_limits_and_bad_input
    assert_equal PC::MIN_JDN, PC.to_jdn(PC::MIN_YEAR, 1, 1)
    assert_equal PC::MAX_JDN, PC.to_jdn(PC::MAX_YEAR, 12, 29)
    assert_equal PC::PersianDate.new(PC::MIN_YEAR, 1, 1), PC.from_jdn(PC::MIN_JDN)
    assert_equal PC::PersianDate.new(PC::MAX_YEAR, 12, 29), PC.from_jdn(PC::MAX_JDN)
    [PC::MIN_JDN - 1, PC::MAX_JDN + 1, 2**64, -2**64].each do |bad|
      assert_raises(RangeError) { PC.from_jdn(bad) }
    end
    [PC::MIN_YEAR - 1, PC::MAX_YEAR + 1, 10**100].each do |bad|
      refute PC.valid_date?(bad, 1, 1)
      assert_raises(ArgumentError) { PC.to_jdn(bad, 1, 1) }
      assert_raises(RangeError) { PC.leap_year?(bad) }
    end
    assert_raises(TypeError) { PC.from_jdn(2_460_756.5) }
    assert_raises(TypeError) { PC.from_jdn('2460756') }
    assert_raises(TypeError) { PC.leap_year?(1404.0) }
    assert_raises(TypeError) { PC.to_jdn(1404, 1.5, 1) }
    assert_raises(TypeError) { PC.from_date('2025-03-21') }
    assert_raises(RangeError) { PC.from_date(Date.new(200_000, 1, 1)) }
    assert PC::MONTH_NAMES_FA.frozen? && PC::NON_LEAP_CORRECTION.frozen?
    assert_raises(FrozenError) { PC::MONTH_NAMES_FA[0] = 'X' }
  end

  # Every year MIN_YEAR..MAX_YEAR: years are contiguous, first and last day round-trip, and the leap
  # years sit where every other implementation (and ICU 77.1+) puts them (checksums).
  def test_every_year_of_the_full_range
    expected = PC::MIN_JDN
    leaps = 0
    nowruz_sum = 0
    (PC::MIN_YEAR..PC::MAX_YEAR).each do |y|
      nowruz = PC.to_jdn(y, 1, 1)
      leap = PC.leap_year?(y) ? 1 : 0
      unless nowruz == expected && PC.from_jdn(nowruz) == PC::PersianDate.new(y, 1, 1) &&
             PC.days_in_month(y, 12) == 29 + leap && PC.from_jdn(nowruz + 364 + leap) == PC::PersianDate.new(y, 12, 29 + leap)
        flunk "year #{y}"
      end
      leaps += leap
      nowruz_sum += nowruz
      expected = nowruz + 365 + leap
    end
    assert_equal [PC::MAX_JDN, 48_485, 389_592_978_180], [expected - 1, leaps, nowruz_sum]
  end
end

Other languages