پرش به محتوای اصلی
فهرست مطالب

پیاده‌سازی · Kotlin

تقویم شمسی (جلالی) در Kotlin

پیاده‌سازی بدون وابستگی تقویم جلالی (هجری شمسی) در Kotlin: تشخیص سال کبیسه، اعتبارسنجی تاریخ، تبدیل به میلادی و شمارهٔ روز جولیانی، روز هفته و روز سال؛ روزبه‌روز برای سال‌های ۱۱۷۸ تا ۳۰۰۰ راستی‌آزمایی شده. مجوز MIT.

پیش‌نیاز
Kotlin (JVM/Android, KMP core)
تست‌شده با
Kotlin 2.4
مقایسه‌شده با
ICU4J نسخهٔ 76.1 تا 79.1
بررسی‌های اختصاصی
سازگار با نسخه‌های قدیمی‌تر اندروید (بدون نیاز به API 30)، -Werror
مجوز
MIT
نسخه
1.0.0

شروع سریع

  1. فایل کد را کپی یا دانلود کنید و در پروژه‌تان بگذارید (بدون هیچ وابستگی).

  2. در صورت تمایل تست‌هایش را هم اجرا کنید. فایل zip همان ساختار پوشه‌ای را دارد که تست‌ها لازم دارند؛ از داخل پوشهٔ زبان:

    implementations/kotlin
    kotlinc *.kt -include-runtime -d t.jar && java -jar t.jar
  3. توابع مشترک را صدا بزنید: راهنمای توابع

کد

PersianCalendar.kt

· ۱۳۰ خط
دانلود
// Copyright (C) 2026 Goudarz Jafari <hi@goudarzjafari.com>
// SPDX-License-Identifier: MIT

/*
 * 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 throw IllegalArgumentException.
 * JVM and Android (the java.time helpers need API 26+ or core library desugaring).
 */
package persiancalendar

import java.time.LocalDate

data class PersianDate(val year: Int, val month: Int, val day: Int)

object PersianCalendar {
    /** Years checked against the astronomical calendar. */
    const val VERIFIED_MIN_YEAR = 1178
    const val VERIFIED_MAX_YEAR = 3000

    /** Accepted input range. Within it every intermediate value fits in 32 bits. */
    const val MIN_YEAR = -100_000
    const val MAX_YEAR = 100_000
    /** 1 Farvardin -100000 (Gregorian -99379-03-29). */
    const val MIN_JDN = -34_576_287L
    /** 29 Esfand 100000 (Gregorian 100622-03-13). */
    const val MAX_JDN = 38_472_562L

    private const val EPOCH_JDN = 1948320L
    private const val UNIX_EPOCH_JDN = 2440588L // JDN of 1970-01-01

    private val CORRECTIONS = intArrayOf(
        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,
    )

    /** Years the 33-year rule calls leap but are not; the next year is leap instead (immutable copy). */
    val NON_LEAP_CORRECTION: List<Int> = java.util.Collections.unmodifiableList(CORRECTIONS.toList())

    // Unmodifiable lists: cannot be changed even when cast to MutableList (works on every Android API level).
    val MONTH_NAMES_FA: List<String> = names("فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد", "شهریور",
        "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند")
    val MONTH_NAMES_EN: List<String> = names("Farvardin", "Ordibehesht", "Khordad", "Tir", "Mordad", "Shahrivar",
        "Mehr", "Aban", "Azar", "Dey", "Bahman", "Esfand")
    val WEEKDAY_NAMES_FA: List<String> = names("شنبه", "یکشنبه", "دوشنبه", "سه‌شنبه", "چهارشنبه", "پنجشنبه", "جمعه")
    val WEEKDAY_NAMES_EN: List<String> = names("Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday")

    private fun names(vararg n: String): List<String> = java.util.Collections.unmodifiableList(n.toList())

    private fun isCorrection(year: Long) =
        year in 1502L..2987L && CORRECTIONS.binarySearch(year.toInt()) >= 0

    private fun checkYear(year: Int) =
        require(year in MIN_YEAR..MAX_YEAR) { "year out of range [$MIN_YEAR, $MAX_YEAR]: $year" }

    private fun checkJdn(jdn: Long) =
        require(jdn in MIN_JDN..MAX_JDN) { "jdn out of range [$MIN_JDN, $MAX_JDN]: $jdn" }

    /** True if the Persian year has 366 days (Esfand has 30 days). */
    fun isLeapYear(year: Int): Boolean {
        checkYear(year)
        return when {
            isCorrection(year.toLong()) -> false
            isCorrection(year - 1L) -> true
            else -> (25L * year + 11).mod(33L) < 8
        }
    }

    /** 29, 30 or 31. */
    fun daysInMonth(year: Int, month: Int): Int {
        checkYear(year)
        return when (month) {
            in 1..6 -> 31
            in 7..11 -> 30
            12 -> if (isLeapYear(year)) 30 else 29
            else -> throw IllegalArgumentException("month out of range [1, 12]: $month")
        }
    }

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

    private fun nowruzJdn(year: Long): Long {
        val jdn = EPOCH_JDN + 365 * (year - 1) + (8 * year + 21).floorDiv(33L)
        return if (isCorrection(year - 1)) jdn - 1 else jdn
    }

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

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

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

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

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

    // JVM / Android (API 26+, or with desugaring) interop
    fun fromLocalDate(date: LocalDate): PersianDate = fromJdn(date.toEpochDay() + UNIX_EPOCH_JDN)
    fun toLocalDate(year: Int, month: Int, day: Int): LocalDate =
        LocalDate.ofEpochDay(toJdn(year, month, day) - UNIX_EPOCH_JDN)
}

تست‌ها

PersianCalendarTest.kt

۱۳۳ خط
Kotlinدانلود
// Copyright (C) 2026 Goudarz Jafari <hi@goudarzjafari.com>
// SPDX-License-Identifier: MIT

// Checks PersianCalendar.kt against /data.
// Run: kotlinc *.kt -include-runtime -d test.jar && java -jar test.jar ../../data
package persiancalendar

import java.io.File
import java.time.LocalDate

private var checks = 0

private fun check(ok: Boolean, context: () -> Any) {
    checks++
    if (!ok) throw AssertionError("failed: ${context()}")
}

fun main(args: Array<String>) {
    val dataDir = args.firstOrNull() ?: "../../data"
    fun csv(name: String) = File(dataDir, name).readLines().drop(1).filter { it.isNotBlank() }.map { it.split(",") }
    val pc = PersianCalendar

    for (r in csv("years.csv")) {
        val y = r[0].toInt()
        val leap = r[1] == "1"
        check(pc.isLeapYear(y) == leap) { "leap $y" }
        check(pc.daysInMonth(y, 12) == if (leap) 30 else 29) { "esfand $y" }
        check(pc.toLocalDate(y, 1, 1) == LocalDate.parse(r[3])) { "nowruz $y" }
        check(pc.toJdn(y, 1, 1) == r[4].toLong()) { "jdn $y" }
        // every day of the year against the ground truth, both directions
        for (doy in 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) { "$y/$m/$d" }
        }
        check(pc.dayOfWeek(y, 1, 1) == r[5].toInt()) { "weekday $y" }
    }
    for (r in csv("test-vectors.csv")) {
        val v = r.map { it.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(PersianCalendar.VERIFIED_MIN_YEAR, 1, 1)
    val lastYear = PersianCalendar.VERIFIED_MAX_YEAR
    val last = pc.toJdn(lastYear, 12, pc.daysInMonth(lastYear, 12))
    var prev = pc.fromJdn(first - 1)
    for (jdn in first..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
    }
    // 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) in listOf(-1000 to 1177, 3001 to 4000)) {
        val a = pc.toJdn(firstYear, 1, 1)
        val b = pc.toJdn(lastYear, 12, pc.daysInMonth(lastYear, 12))
        var p = pc.fromJdn(a - 1)
        for (jdn in a..b) {
            val d = pc.fromJdn(jdn)
            check(pc.isValidDate(d.year, d.month, d.day) && pc.toJdn(d.year, d.month, d.day) == jdn) { jdn }
            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) { jdn }
            p = d
        }
    }
    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(runCatching { 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(PersianCalendar.WEEKDAY_NAMES_EN[pc.dayOfWeek(1404, 1, 1)] == "Friday") { "friday" }
    // Limits: exact boundaries, and fast rejection of anything outside (no hang, no overflow).
    check(pc.toJdn(PersianCalendar.MIN_YEAR, 1, 1) == PersianCalendar.MIN_JDN) { "MIN_JDN" }
    check(pc.toJdn(PersianCalendar.MAX_YEAR, 12, 29) == PersianCalendar.MAX_JDN) { "MAX_JDN" }
    check(pc.fromJdn(PersianCalendar.MIN_JDN) == PersianDate(-100_000, 1, 1)) { "from MIN_JDN" }
    check(pc.fromJdn(PersianCalendar.MAX_JDN) == PersianDate(100_000, 12, 29)) { "from MAX_JDN" }
    for (bad in listOf(PersianCalendar.MIN_JDN - 1, PersianCalendar.MAX_JDN + 1, Long.MAX_VALUE, Long.MIN_VALUE, 1L shl 53)) {
        check(runCatching { pc.fromJdn(bad) }.exceptionOrNull() is IllegalArgumentException) { "fromJdn $bad" }
    }
    for (bad in listOf(PersianCalendar.MIN_YEAR - 1, PersianCalendar.MAX_YEAR + 1, Int.MAX_VALUE, Int.MIN_VALUE)) {
        check(!pc.isValidDate(bad, 1, 1)) { "isValidDate $bad" }
        check(runCatching { pc.toJdn(bad, 1, 1) }.exceptionOrNull() is IllegalArgumentException) { "toJdn $bad" }
        check(runCatching { pc.isLeapYear(bad) }.exceptionOrNull() is IllegalArgumentException) { "isLeapYear $bad" }
    }
    check(runCatching { pc.fromLocalDate(LocalDate.MAX) }.exceptionOrNull() is IllegalArgumentException) { "LocalDate.MAX" }
    @Suppress("UNCHECKED_CAST")
    check(runCatching { (PersianCalendar.MONTH_NAMES_FA as MutableList<String>)[0] = "X" }.isFailure) { "immutable names" }
    @Suppress("UNCHECKED_CAST")
    check(runCatching { (PersianCalendar.NON_LEAP_CORRECTION as MutableList<Int>)[0] = 1 }.isFailure) { "immutable table" }
    check(PersianCalendar.WEEKDAY_NAMES_FA[3] == "سه‌شنبه") { "ZWNJ" }
    // 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).
    var expected = PersianCalendar.MIN_JDN
    var leaps = 0L
    var nowruzSum = 0L
    for (y in PersianCalendar.MIN_YEAR..PersianCalendar.MAX_YEAR) {
        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) { "year $y" }
        }
        leaps += leap
        nowruzSum += nowruz
        expected = nowruz + 365 + leap
    }
    check(expected - 1 == PersianCalendar.MAX_JDN && leaps == 48_485L && nowruzSum == 389_592_978_180L) { "full-range checksums" }
    println("OK: $checks checks passed")
}

زبان‌های دیگر