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

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

- پیش‌نیاز: C# (.NET 6+)
- تست‌شده با: .NET 8
- مقایسه‌شده با: ICU4C نسخهٔ 76.1 تا 79.1 (P/Invoke)؛ `PersianCalendar` در ‎.NET (که از ۱۵۳۵ خطا داره)
- بررسی‌های اختصاصی: تبدیل هشدارهای کامپایلر به خطا، لیست‌های فقط‌خواندنی
- مجوز: MIT
- نسخه: 1.0.0
- دانلود همهٔ فایل‌ها (zip): https://goudarzjafari.com/persian-calendar/files/persian-calendar-csharp.zip

## شروع سریع

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

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

   ```sh
   cd tests && dotnet run
   ```

3. توابع مشترک را صدا بزنید: https://goudarzjafari.com/fa/persian-calendar/implementations/#common-api

## SolarHijri.cs

```csharp
// 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.
//
// Named SolarHijri to avoid a clash with System.Globalization.PersianCalendar
// (which is correct only up to 1535 AP; see docs).
// Inputs outside MinYear..MaxYear / MinJdn..MaxJdn throw ArgumentOutOfRangeException;
// invalid dates throw ArgumentException. Thread-safe. Requires .NET 6+ (DateOnly).

using System;
using System.Collections.Generic;

namespace SolarHijriCalendar;

public readonly record struct PersianDate(int Year, int Month, int Day);

public static class SolarHijri
{
    /// <summary>Years checked against the astronomical calendar.</summary>
    public const int VerifiedMinYear = 1178;
    public const int VerifiedMaxYear = 3000;

    /// <summary>Accepted input range. Within it every intermediate value fits in 32 bits.</summary>
    public const int MinYear = -100_000;
    public const int MaxYear = 100_000;
    /// <summary>1 Farvardin -100000 (Gregorian -99379-03-29).</summary>
    public const long MinJdn = -34_576_287;
    /// <summary>29 Esfand 100000 (Gregorian 100622-03-13).</summary>
    public const long MaxJdn = 38_472_562;

    private const long EpochJdn = 1948320;
    // JDN of 0001-01-01 (DateOnly.DayNumber == 0).
    private const long DayNumberEpochJdn = 1721426;

    // Years the 33-year rule calls leap but are not; the next year is leap instead.
    private static readonly HashSet<long> NonLeapCorrection = new()
    {
        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,
    };

    public static readonly IReadOnlyList<string> MonthNamesFa =
        Array.AsReadOnly(new[] { "فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد", "شهریور", "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند" });
    public static readonly IReadOnlyList<string> MonthNamesEn =
        Array.AsReadOnly(new[] { "Farvardin", "Ordibehesht", "Khordad", "Tir", "Mordad", "Shahrivar", "Mehr", "Aban", "Azar", "Dey", "Bahman", "Esfand" });
    public static readonly IReadOnlyList<string> WeekdayNamesFa =
        Array.AsReadOnly(new[] { "شنبه", "یکشنبه", "دوشنبه", "سه‌شنبه", "چهارشنبه", "پنجشنبه", "جمعه" });
    public static readonly IReadOnlyList<string> WeekdayNamesEn =
        Array.AsReadOnly(new[] { "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" });

    // C# / and % truncate toward zero; the formulas need floor semantics.
    private static long FloorDiv(long a, long b) => a / b - ((a % b != 0) && ((a < 0) != (b < 0)) ? 1 : 0);
    private static long FloorMod(long a, long b) => a - b * FloorDiv(a, b);

    private static void CheckYear(int year)
    {
        if (year < MinYear || year > MaxYear)
            throw new ArgumentOutOfRangeException(nameof(year), year, $"year out of range [{MinYear}, {MaxYear}]");
    }

    private static void CheckJdn(long jdn)
    {
        if (jdn < MinJdn || jdn > MaxJdn)
            throw new ArgumentOutOfRangeException(nameof(jdn), jdn, $"jdn out of range [{MinJdn}, {MaxJdn}]");
    }

    /// <summary>True if the Persian year has 366 days (Esfand has 30 days).</summary>
    public static bool IsLeapYear(int year)
    {
        CheckYear(year);
        if (NonLeapCorrection.Contains(year)) return false;
        if (NonLeapCorrection.Contains(year - 1L)) return true;
        return FloorMod(25L * year + 11, 33) < 8;
    }

    /// <summary>29, 30 or 31.</summary>
    public static int DaysInMonth(int year, int month)
    {
        CheckYear(year);
        if (month < 1 || month > 12) throw new ArgumentOutOfRangeException(nameof(month), month, "month out of range [1, 12]");
        if (month <= 6) return 31;
        if (month <= 11) return 30;
        return IsLeapYear(year) ? 30 : 29;
    }

    /// <summary>True for a real Persian date in the accepted range; never throws.</summary>
    public static bool IsValidDate(int year, int month, int day) =>
        year >= MinYear && year <= MaxYear && month >= 1 && month <= 12 && day >= 1 && day <= DaysInMonth(year, month);

    private static long NowruzJdn(long year)
    {
        long jdn = EpochJdn + 365 * (year - 1) + FloorDiv(8 * year + 21, 33);
        if (NonLeapCorrection.Contains(year - 1)) jdn -= 1;
        return jdn;
    }

    private static int DaysBeforeMonth(int month) => month <= 7 ? 31 * (month - 1) : 30 * (month - 1) + 6;

    /// <summary>Julian Day Number of a Persian date.</summary>
    public static long ToJdn(int year, int month, int day)
    {
        if (!IsValidDate(year, month, day))
            throw new ArgumentException($"invalid Persian date: {year}/{month}/{day}");
        return NowruzJdn(year) + DaysBeforeMonth(month) + day - 1;
    }

    /// <summary>Persian date of a Julian Day Number in <see cref="MinJdn"/>..<see cref="MaxJdn"/>.</summary>
    public static PersianDate FromJdn(long jdn)
    {
        CheckJdn(jdn);
        long year = 1 + FloorDiv(33 * (jdn - EpochJdn) + 3, 12053);
        while (jdn >= NowruzJdn(year + 1)) year++;
        while (jdn < NowruzJdn(year)) year--;
        int doy = (int)(jdn - NowruzJdn(year)); // 0-based
        if (doy < 186) return new PersianDate((int)year, doy / 31 + 1, doy % 31 + 1);
        doy -= 186;
        return new PersianDate((int)year, doy / 30 + 7, doy % 30 + 1);
    }

    public static PersianDate FromDateOnly(DateOnly date) => FromJdn(date.DayNumber + DayNumberEpochJdn);

    public static DateOnly ToDateOnly(int year, int month, int day) =>
        DateOnly.FromDayNumber((int)(ToJdn(year, month, day) - DayNumberEpochJdn));

    /// <summary>0 = Saturday (شنبه) ... 6 = Friday (جمعه).</summary>
    public static int DayOfWeek(int year, int month, int day) => (int)FloorMod(ToJdn(year, month, day) + 2, 7);

    /// <summary>1 ... 365/366.</summary>
    public static int DayOfYear(int year, int month, int day)
    {
        if (!IsValidDate(year, month, day))
            throw new ArgumentException($"invalid Persian date: {year}/{month}/{day}");
        return DaysBeforeMonth(month) + day;
    }
}
```

## tests/Program.cs

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

// Checks SolarHijri against /data. Run: dotnet run --project implementations/csharp/tests
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SolarHijriCalendar;

int checks = 0;
void Check(bool ok, object context)
{
    checks++;
    if (!ok) throw new Exception($"failed: {context}");
}

string dataDir = Environment.GetEnvironmentVariable("DATA_DIR")
    ?? Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "..", "..", "data");
string[][] Csv(string name) => File.ReadAllLines(Path.Combine(dataDir, name))
    .Skip(1).Where(l => l.Length > 0).Select(l => l.Split(',')).ToArray();

foreach (var r in Csv("years.csv"))
{
    int y = int.Parse(r[0]);
    bool leap = r[1] == "1";
    Check(SolarHijri.IsLeapYear(y) == leap, $"leap {y}");
    Check(SolarHijri.DaysInMonth(y, 12) == (leap ? 30 : 29), $"esfand {y}");
    Check(SolarHijri.ToDateOnly(y, 1, 1) == DateOnly.Parse(r[3], System.Globalization.CultureInfo.InvariantCulture), $"nowruz {y}");
    Check(SolarHijri.ToJdn(y, 1, 1) == long.Parse(r[4]), $"jdn {y}");
    // every day of the year against the ground truth, both directions
    for (int doy = 0; doy < int.Parse(r[2]); doy++)
    {
        int m = doy < 186 ? doy / 31 + 1 : (doy - 186) / 30 + 7;
        int d = doy < 186 ? doy % 31 + 1 : (doy - 186) % 30 + 1;
        long jdn = long.Parse(r[4]) + doy;
        Check(SolarHijri.FromJdn(jdn) == new PersianDate(y, m, d) && SolarHijri.ToJdn(y, m, d) == jdn, $"{y}/{m}/{d}");
    }
    Check(SolarHijri.DayOfWeek(y, 1, 1) == int.Parse(r[5]), $"weekday {y}");
}

foreach (var r in Csv("test-vectors.csv"))
{
    var v = r.Select(int.Parse).ToArray();
    var p = new PersianDate(v[0], v[1], v[2]);
    var g = new DateOnly(v[3], v[4], v[5]);
    Check(SolarHijri.ToDateOnly(v[0], v[1], v[2]) == g, p);
    Check(SolarHijri.FromDateOnly(g) == p, g);
    Check(SolarHijri.ToJdn(v[0], v[1], v[2]) == v[6], p);
    Check(SolarHijri.FromJdn(v[6]) == p, p);
    Check(SolarHijri.DayOfWeek(v[0], v[1], v[2]) == v[7], p);
}

long first = SolarHijri.ToJdn(SolarHijri.VerifiedMinYear, 1, 1);
long last = SolarHijri.ToJdn(SolarHijri.VerifiedMaxYear, 12, SolarHijri.DaysInMonth(SolarHijri.VerifiedMaxYear, 12));
var prev = SolarHijri.FromJdn(first - 1);
for (long jdn = first; jdn <= last; jdn++)
{
    var d = SolarHijri.FromJdn(jdn);
    Check(SolarHijri.IsValidDate(d.Year, d.Month, d.Day), jdn);
    Check(SolarHijri.ToJdn(d.Year, d.Month, d.Day) == jdn, jdn);
    bool 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(SolarHijri.ToJdn(-1000, 1, 1) == 1582713, "-1000");
Check(SolarHijri.ToJdn(0, 1, 1) == 1947955, "0");
Check(SolarHijri.ToJdn(4000, 1, 1) == 3408925, "4000");
Check(SolarHijri.FromJdn(0) == new PersianDate(-5334, 9, 3), "jdn 0");
Check(SolarHijri.DayOfWeek(-1000, 1, 1) == 1, "weekday -1000");
Check(SolarHijri.IsLeapYear(-3) && !SolarHijri.IsLeapYear(-1000), "negative leap years");
foreach (var (firstYear, lastYear) in new[] { (-1000, 1177), (3001, 4000) })
{
    long a = SolarHijri.ToJdn(firstYear, 1, 1);
    long b = SolarHijri.ToJdn(lastYear, 12, SolarHijri.DaysInMonth(lastYear, 12));
    var p = SolarHijri.FromJdn(a - 1);
    for (long jdn = a; jdn <= b; jdn++)
    {
        var d = SolarHijri.FromJdn(jdn);
        Check(SolarHijri.IsValidDate(d.Year, d.Month, d.Day) && SolarHijri.ToJdn(d.Year, d.Month, d.Day) == jdn, jdn);
        bool 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(SolarHijri.IsValidDate(1403, 12, 30), "1403/12/30");
Check(!SolarHijri.IsValidDate(1404, 12, 30), "1404/12/30");
Check(SolarHijri.IsValidDate(1404, 6, 31), "1404/6/31");
Check(!SolarHijri.IsValidDate(1404, 7, 31), "1404/7/31");
Check(!SolarHijri.IsValidDate(1404, 13, 1), "1404/13/1");
Check(!SolarHijri.IsValidDate(1404, 0, 1), "1404/0/1");
Check(!SolarHijri.IsValidDate(1404, 1, 0), "1404/1/0");
try { SolarHijri.ToJdn(1404, 12, 30); Check(false, "should throw"); }
catch (ArgumentException) { checks++; }
Check(SolarHijri.FromDateOnly(new DateOnly(2025, 3, 21)) == new PersianDate(1404, 1, 1), "2025-03-21");
Check(SolarHijri.FromDateOnly(new DateOnly(1979, 2, 11)) == new PersianDate(1357, 11, 22), "1979-02-11");
Check(SolarHijri.DayOfYear(1404, 7, 1) == 187, "doy");
Check(SolarHijri.WeekdayNamesEn[SolarHijri.DayOfWeek(1404, 1, 1)] == "Friday", "friday");
// Limits: exact boundaries, and fast rejection of anything outside (no hang, no overflow).
Check(SolarHijri.ToJdn(SolarHijri.MinYear, 1, 1) == SolarHijri.MinJdn, "MinJdn");
Check(SolarHijri.ToJdn(SolarHijri.MaxYear, 12, 29) == SolarHijri.MaxJdn, "MaxJdn");
Check(SolarHijri.FromJdn(SolarHijri.MinJdn) == new PersianDate(-100_000, 1, 1), "from MinJdn");
Check(SolarHijri.FromJdn(SolarHijri.MaxJdn) == new PersianDate(100_000, 12, 29), "from MaxJdn");
bool Throws<TException>(Action a) where TException : Exception
{
    try { a(); return false; } catch (TException) { return true; }
}
foreach (long bad in new[] { SolarHijri.MinJdn - 1, SolarHijri.MaxJdn + 1, long.MaxValue, long.MinValue, 1L << 53 })
    Check(Throws<ArgumentOutOfRangeException>(() => SolarHijri.FromJdn(bad)), $"FromJdn {bad}");
foreach (int bad in new[] { SolarHijri.MinYear - 1, SolarHijri.MaxYear + 1, int.MaxValue, int.MinValue })
{
    Check(!SolarHijri.IsValidDate(bad, 1, 1), $"IsValidDate {bad}");
    Check(Throws<ArgumentException>(() => SolarHijri.ToJdn(bad, 1, 1)), $"ToJdn {bad}");
    Check(Throws<ArgumentOutOfRangeException>(() => SolarHijri.IsLeapYear(bad)), $"IsLeapYear {bad}");
}
Check(Throws<NotSupportedException>(() => ((IList<string>)SolarHijri.MonthNamesFa)[0] = "X"), "immutable names");
Check(SolarHijri.MonthNamesFa is not string[], "names are not a writable array");
// 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).
long expectedNowruz = SolarHijri.MinJdn, leaps = 0, nowruzSum = 0;
for (int y = SolarHijri.MinYear; y <= SolarHijri.MaxYear; y++)
{
    long nowruz = SolarHijri.ToJdn(y, 1, 1);
    int leap = SolarHijri.IsLeapYear(y) ? 1 : 0;
    if (nowruz != expectedNowruz || SolarHijri.FromJdn(nowruz) != new PersianDate(y, 1, 1)
        || SolarHijri.DaysInMonth(y, 12) != 29 + leap || SolarHijri.FromJdn(nowruz + 364 + leap) != new PersianDate(y, 12, 29 + leap))
        Check(false, $"year {y}");
    leaps += leap;
    nowruzSum += nowruz;
    expectedNowruz = nowruz + 365 + leap;
}
Check(expectedNowruz - 1 == SolarHijri.MaxJdn && leaps == 48_485 && nowruzSum == 389_592_978_180, "full-range checksums");
Console.WriteLine($"OK: {checks} checks passed");
```

## tests/Tests.csproj

```markup
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>disable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <Compile Include="../SolarHijri.cs" />
  </ItemGroup>

</Project>
```

---

نشانی صفحه: https://goudarzjafari.com/fa/persian-calendar/implementations/csharp/
مجوز: متن CC BY 4.0، کد MIT، داده CC0 1.0. نسخهٔ 1.0.0 از https://github.com/Goudarz/PersianCalendar
