Skip to main content
Contents

Implementation · Scala

Persian (Jalali) calendar in Scala

Dependency-free Scala 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
Scala 3
Tested with
Scala 3.9
Cross-checked against
ICU4J 76.1–79.1
Language-specific checks
LocalDate.MAX boundary checks
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/scala
    scala run . --main-class persiancalendar.PersianCalendarTest -- ../../data
  3. Call the shared API: function reference

Source

PersianCalendar.scala

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

/*
 * Solar Hijri (Persian, Jalali, Shamsi) calendar (Scala 3).
 *
 * 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 MinYear..MaxYear / MinJdn..MaxJdn throw IllegalArgumentException.
 */
package persiancalendar

import java.time.LocalDate

final case class PersianDate(year: Int, month: Int, day: Int)

object PersianCalendar {
  /** Years checked against the astronomical calendar. */
  val VerifiedMinYear = 1178
  val VerifiedMaxYear = 3000

  /** Accepted input range. Within it every intermediate value fits in 32 bits. */
  val MinYear: Int = -100000
  val MaxYear: Int = 100000
  /** 1 Farvardin -100000 (Gregorian -99379-03-29). */
  val MinJdn: Long = -34576287L
  /** 29 Esfand 100000 (Gregorian 100622-03-13). */
  val MaxJdn: Long = 38472562L

  private val EpochJdn = 1948320L
  private val UnixEpochJdn = 2440588L // JDN of 1970-01-01

  /** Years the 33-year rule calls leap but are not; the next year is leap instead. */
  val NonLeapCorrection: Set[Int] = 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
  )

  val MonthNamesFa: Vector[String] = Vector("فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد", "شهریور",
    "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند")
  val MonthNamesEn: Vector[String] = Vector("Farvardin", "Ordibehesht", "Khordad", "Tir", "Mordad", "Shahrivar",
    "Mehr", "Aban", "Azar", "Dey", "Bahman", "Esfand")
  val WeekdayNamesFa: Vector[String] = Vector("شنبه", "یکشنبه", "دوشنبه", "سه‌شنبه", "چهارشنبه", "پنجشنبه", "جمعه")
  val WeekdayNamesEn: Vector[String] = Vector("Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday")

  private def isCorrection(year: Long): Boolean =
    year >= 1502 && year <= 2987 && NonLeapCorrection.contains(year.toInt)

  private def checkYear(year: Int): Unit =
    require(year >= MinYear && year <= MaxYear, s"year out of range [$MinYear, $MaxYear]: $year")

  private def checkJdn(jdn: Long): Unit =
    require(jdn >= MinJdn && jdn <= MaxJdn, s"jdn out of range [$MinJdn, $MaxJdn]: $jdn")

  /** True if the Persian year has 366 days (Esfand has 30 days). */
  def isLeapYear(year: Int): Boolean =
    checkYear(year)
    if (isCorrection(year.toLong)) false
    else if (isCorrection(year - 1L)) true
    else Math.floorMod(25L * year + 11, 33L) < 8

  /** 29, 30 or 31. */
  def daysInMonth(year: Int, month: Int): Int = { checkYear(year); month } match {
    case m if m >= 1 && m <= 6  => 31
    case m if m >= 7 && m <= 11 => 30
    case 12                     => if (isLeapYear(year)) 30 else 29
    case m                      => throw new IllegalArgumentException(s"month out of range [1, 12]: $m")
  }

  /** True for a real Persian date in the accepted range; never throws. */
  def isValidDate(year: Int, month: Int, day: Int): Boolean =
    year >= MinYear && year <= MaxYear && month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth(year, month)

  private def nowruzJdn(year: Long): Long = {
    val jdn = EpochJdn + 365 * (year - 1) + Math.floorDiv(8 * year + 21, 33L)
    if (isCorrection(year - 1)) jdn - 1 else jdn
  }

  private def daysBeforeMonth(month: Int): Int =
    if (month <= 7) 31 * (month - 1) else 30 * (month - 1) + 6

  /** Julian Day Number of a Persian date. */
  def toJdn(year: Int, month: Int, day: Int): Long = {
    require(isValidDate(year, month, day), s"invalid Persian date: $year/$month/$day")
    nowruzJdn(year.toLong) + daysBeforeMonth(month) + day - 1
  }

  /** Persian date of a Julian Day Number in MinJdn..MaxJdn. */
  def fromJdn(jdn: Long): PersianDate = {
    checkJdn(jdn)
    var year = 1 + Math.floorDiv(33 * (jdn - EpochJdn) + 3, 12053L)
    while (jdn >= nowruzJdn(year + 1)) year += 1
    while (jdn < nowruzJdn(year)) year -= 1
    val doy = (jdn - nowruzJdn(year)).toInt // 0-based
    if (doy < 186) PersianDate(year.toInt, doy / 31 + 1, doy % 31 + 1)
    else PersianDate(year.toInt, (doy - 186) / 30 + 7, (doy - 186) % 30 + 1)
  }

  def fromLocalDate(date: LocalDate): PersianDate = fromJdn(date.toEpochDay + UnixEpochJdn)

  def toLocalDate(year: Int, month: Int, day: Int): LocalDate =
    LocalDate.ofEpochDay(toJdn(year, month, day) - UnixEpochJdn)

  /** 0 = Saturday (شنبه) ... 6 = Friday (جمعه). */
  def dayOfWeek(year: Int, month: Int, day: Int): Int =
    Math.floorMod(toJdn(year, month, day) + 2, 7L).toInt

  /** 1 ... 365/366. */
  def dayOfYear(year: Int, month: Int, day: Int): Int = {
    require(isValidDate(year, month, day), s"invalid Persian date: $year/$month/$day")
    daysBeforeMonth(month) + day
  }
}

Tests

PersianCalendarTest.scala

134 lines
ScalaDownload
// Copyright (C) 2026 Goudarz Jafari <hi@goudarzjafari.com>
// SPDX-License-Identifier: MIT

// Checks PersianCalendar.scala against /data.
// Run: scala run . --main-class persiancalendar.PersianCalendarTest -- ../../data
package persiancalendar

import java.nio.file.{Files, Path}
import java.time.LocalDate
import scala.jdk.CollectionConverters._

object PersianCalendarTest {
  private var checks = 0L

  private def check(ok: Boolean, context: => Any): Unit = {
    checks += 1
    if (!ok) throw new AssertionError(s"failed: $context")
  }

  def main(args: Array[String]): Unit = {
    val dataDir = args.headOption.getOrElse("../../data")
    def csv(name: String): Seq[Array[String]] =
      Files.readAllLines(Path.of(dataDir, name)).asScala.toSeq.drop(1).filter(_.nonEmpty).map(_.split(","))
    val pc = PersianCalendar

    for (r <- csv("years.csv")) {
      val y = r(0).toInt
      val leap = r(1) == "1"
      check(pc.isLeapYear(y) == leap, s"leap $y")
      check(pc.daysInMonth(y, 12) == (if (leap) 30 else 29), s"esfand $y")
      check(pc.toLocalDate(y, 1, 1) == LocalDate.parse(r(3)), s"nowruz $y")
      check(pc.toJdn(y, 1, 1) == r(4).toLong, s"jdn $y")
      // every day of the year against the ground truth, both directions
      for (doy <- 0 until r(2).toInt) {
        val m = if (doy < 186) doy / 31 + 1 else (doy - 186) / 30 + 7
        val d = if (doy < 186) doy % 31 + 1 else (doy - 186) % 30 + 1
        val jdn = r(4).toLong + doy
        check(pc.fromJdn(jdn) == PersianDate(y, m, d) && pc.toJdn(y, m, d) == jdn, s"$y/$m/$d")
      }
      check(pc.dayOfWeek(y, 1, 1) == r(5).toInt, s"weekday $y")
    }

    for (r <- csv("test-vectors.csv")) {
      val v = r.map(_.toInt)
      val p = PersianDate(v(0), v(1), v(2))
      val g = LocalDate.of(v(3), v(4), v(5))
      check(pc.toLocalDate(v(0), v(1), v(2)) == g, p)
      check(pc.fromLocalDate(g) == p, g)
      check(pc.toJdn(v(0), v(1), v(2)) == v(6).toLong, p)
      check(pc.fromJdn(v(6).toLong) == p, p)
      check(pc.dayOfWeek(v(0), v(1), v(2)) == v(7), p)
    }

    val first = pc.toJdn(pc.VerifiedMinYear, 1, 1)
    val last = pc.toJdn(pc.VerifiedMaxYear, 12, pc.daysInMonth(pc.VerifiedMaxYear, 12))
    var prev = pc.fromJdn(first - 1)
    var jdn = first
    while (jdn <= last) {
      val d = pc.fromJdn(jdn)
      check(pc.toJdn(d.year, d.month, d.day) == jdn, jdn)
      val 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)))
      check(consecutive, jdn)
      prev = d
      jdn += 1
    }

    // Extrapolated years: years <= 0 make intermediate values negative (floor division matters).
    check(pc.toJdn(-1000, 1, 1) == 1582713L, "-1000")
    check(pc.toJdn(0, 1, 1) == 1947955L, "0")
    check(pc.toJdn(4000, 1, 1) == 3408925L, "4000")
    check(pc.fromJdn(0) == PersianDate(-5334, 9, 3), "jdn 0")
    check(pc.dayOfWeek(-1000, 1, 1) == 1, "weekday -1000")
    check(pc.isLeapYear(-3) && !pc.isLeapYear(-1000), "negative leap years")
    for ((firstYear, lastYear) <- Seq((-1000, 1177), (3001, 4000))) {
      val a = pc.toJdn(firstYear, 1, 1)
      val b = pc.toJdn(lastYear, 12, pc.daysInMonth(lastYear, 12))
      var p = pc.fromJdn(a - 1)
      var j = a
      while (j <= b) {
        val d = pc.fromJdn(j)
        check(pc.isValidDate(d.year, d.month, d.day) && pc.toJdn(d.year, d.month, d.day) == j, j)
        val consecutive = (d.day == p.day + 1 && d.month == p.month && d.year == p.year) ||
          (d.day == 1 && ((d.month == p.month + 1 && d.year == p.year) ||
            (d.month == 1 && p.month == 12 && d.year == p.year + 1)))
        check(consecutive, j)
        p = d
        j += 1
      }
    }
    check(pc.isValidDate(1403, 12, 30), "1403/12/30")
    check(!pc.isValidDate(1404, 12, 30), "1404/12/30")
    check(pc.isValidDate(1404, 6, 31), "1404/6/31")
    check(!pc.isValidDate(1404, 7, 31), "1404/7/31")
    check(!pc.isValidDate(1404, 13, 1), "1404/13/1")
    check(!pc.isValidDate(1404, 0, 1), "1404/0/1")
    check(!pc.isValidDate(1404, 1, 0), "1404/1/0")
    check(scala.util.Try(pc.toJdn(1404, 12, 30)).isFailure, "should throw")
    check(pc.fromLocalDate(LocalDate.of(2025, 3, 21)) == PersianDate(1404, 1, 1), "2025-03-21")
    check(pc.fromLocalDate(LocalDate.of(1979, 2, 11)) == PersianDate(1357, 11, 22), "1979-02-11")
    check(pc.dayOfYear(1404, 7, 1) == 187, "doy")
    check(pc.WeekdayNamesEn(pc.dayOfWeek(1404, 1, 1)) == "Friday", "friday")
    // Limits: exact boundaries, and fast rejection of anything outside (no hang, no overflow).
    check(pc.toJdn(pc.MinYear, 1, 1) == pc.MinJdn, "MinJdn")
    check(pc.toJdn(pc.MaxYear, 12, 29) == pc.MaxJdn, "MaxJdn")
    check(pc.fromJdn(pc.MinJdn) == PersianDate(-100000, 1, 1), "from MinJdn")
    check(pc.fromJdn(pc.MaxJdn) == PersianDate(100000, 12, 29), "from MaxJdn")
    def illegal(f: => Any): Boolean = scala.util.Try(f).failed.toOption.exists(_.isInstanceOf[IllegalArgumentException])
    for (bad <- Seq(pc.MinJdn - 1, pc.MaxJdn + 1, Long.MaxValue, Long.MinValue, 1L << 53)) check(illegal(pc.fromJdn(bad)), s"fromJdn $bad")
    for (bad <- Seq(pc.MinYear - 1, pc.MaxYear + 1, Int.MaxValue, Int.MinValue)) {
      check(!pc.isValidDate(bad, 1, 1), s"isValidDate $bad")
      check(illegal(pc.toJdn(bad, 1, 1)), s"toJdn $bad")
      check(illegal(pc.isLeapYear(bad)), s"isLeapYear $bad")
    }
    check(illegal(pc.fromLocalDate(LocalDate.MAX)), "LocalDate.MAX")
    // Every year MinYear..MaxYear: 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).
    var expected = pc.MinJdn
    var leaps = 0L
    var nowruzSum = 0L
    for (y <- pc.MinYear to pc.MaxYear) {
      val nowruz = pc.toJdn(y, 1, 1)
      val leap = if (pc.isLeapYear(y)) 1 else 0
      if (nowruz != expected || pc.fromJdn(nowruz) != PersianDate(y, 1, 1) || pc.daysInMonth(y, 12) != 29 + leap ||
          pc.fromJdn(nowruz + 364 + leap) != PersianDate(y, 12, 29 + leap)) check(false, s"year $y")
      leaps += leap
      nowruzSum += nowruz
      expected = nowruz + 365 + leap
    }
    check(expected - 1 == pc.MaxJdn && leaps == 48485L && nowruzSum == 389592978180L, "full-range checksums")
    println(s"OK: $checks checks passed")
  }
}

Other languages