Skip to main content
Contents

Implementation · Java

Persian (Jalali) calendar in Java

Dependency-free Java 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
Java 16+
Tested with
Java 26
Cross-checked against
ICU4J 76.1–79.1, every year of the full range
Language-specific checks
-Xlint:all -Werror, unmodifiable Lists, LocalDate.MIN/MAX
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/java
    javac -d out *.java && java -cp out PersianCalendarTest
  3. Call the shared API: function reference

Source

PersianCalendar.java

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

import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;

/**
 * Solar Hijri (Persian, Jalali, Shamsi) calendar.
 *
 * <p>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.
 *
 * <p>Accepted input: years {@link #MIN_YEAR}..{@link #MAX_YEAR} and day numbers {@link #MIN_JDN}..{@link #MAX_JDN};
 * anything else throws {@link IllegalArgumentException}. All methods are thread-safe and allocation-free
 * except for the returned records.
 *
 * <p>Requires Java 16+ (records).
 */
public final class PersianCalendar {
    private PersianCalendar() {}

    public record PersianDate(int year, int month, int day) {}

    /** Years checked against the astronomical calendar. */
    public static final int VERIFIED_MIN_YEAR = 1178;
    public static final int VERIFIED_MAX_YEAR = 3000;

    /** Accepted input range. Within it every intermediate value fits in 32 bits. */
    public static final int MIN_YEAR = -100_000;
    public static final int MAX_YEAR = 100_000;
    /** 1 Farvardin -100000 (Gregorian -99379-03-29). */
    public static final long MIN_JDN = -34_576_287;
    /** 29 Esfand 100000 (Gregorian 100622-03-13). */
    public static final long MAX_JDN = 38_472_562;

    private static final long EPOCH_JDN = 1948320;
    /** JDN of 1970-01-01, to convert from/to {@link LocalDate#toEpochDay()}. */
    private static final long UNIX_EPOCH_JDN = 2440588;

    /** Sorted. Years the 33-year rule calls leap but are not; the next year is leap instead. */
    private static final int[] NON_LEAP_CORRECTION = {
        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,
    };

    // Immutable lists: unlike public arrays, callers cannot change them.
    public static final List<String> MONTH_NAMES_FA = List.of("فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد",
        "شهریور", "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند");
    public static final List<String> MONTH_NAMES_EN = List.of("Farvardin", "Ordibehesht", "Khordad", "Tir",
        "Mordad", "Shahrivar", "Mehr", "Aban", "Azar", "Dey", "Bahman", "Esfand");
    public static final List<String> WEEKDAY_NAMES_FA = List.of("شنبه", "یکشنبه", "دوشنبه", "سه‌شنبه",
        "چهارشنبه", "پنجشنبه", "جمعه");
    public static final List<String> WEEKDAY_NAMES_EN = List.of("Saturday", "Sunday", "Monday", "Tuesday",
        "Wednesday", "Thursday", "Friday");

    private static boolean isCorrection(long year) {
        return year >= NON_LEAP_CORRECTION[0] && year <= NON_LEAP_CORRECTION[NON_LEAP_CORRECTION.length - 1]
            && Arrays.binarySearch(NON_LEAP_CORRECTION, (int) year) >= 0;
    }

    private static void checkYear(int year) {
        if (year < MIN_YEAR || year > MAX_YEAR) {
            throw new IllegalArgumentException("year out of range [" + MIN_YEAR + ", " + MAX_YEAR + "]: " + year);
        }
    }

    private static void checkJdn(long jdn) {
        if (jdn < MIN_JDN || jdn > MAX_JDN) {
            throw new IllegalArgumentException("jdn out of range [" + MIN_JDN + ", " + MAX_JDN + "]: " + jdn);
        }
    }

    /** True if the Persian year has 366 days (Esfand has 30 days). */
    public static boolean isLeapYear(int year) {
        checkYear(year);
        if (isCorrection(year)) return false;
        if (isCorrection(year - 1L)) return true;
        return Math.floorMod(25L * year + 11, 33) < 8;
    }

    /** 29, 30 or 31. */
    public static int daysInMonth(int year, int month) {
        checkYear(year);
        if (month < 1 || month > 12) throw new IllegalArgumentException("month out of range [1, 12]: " + month);
        if (month <= 6) return 31;
        if (month <= 11) return 30;
        return isLeapYear(year) ? 30 : 29;
    }

    /** True for a real Persian date in the accepted range; never throws. */
    public static boolean isValidDate(int year, int month, int day) {
        return year >= MIN_YEAR && year <= MAX_YEAR && month >= 1 && month <= 12
            && day >= 1 && day <= daysInMonth(year, month);
    }

    private static long nowruzJdn(long year) {
        long jdn = EPOCH_JDN + 365 * (year - 1) + Math.floorDiv(8 * year + 21, 33);
        if (isCorrection(year - 1)) jdn -= 1;
        return jdn;
    }

    private static int daysBeforeMonth(int month) {
        return month <= 7 ? 31 * (month - 1) : 30 * (month - 1) + 6;
    }

    private static void checkDate(int year, int month, int day) {
        if (!isValidDate(year, month, day)) {
            throw new IllegalArgumentException("invalid Persian date: " + year + "/" + month + "/" + day);
        }
    }

    /** Julian Day Number of a Persian date. */
    public static long toJdn(int year, int month, int day) {
        checkDate(year, month, day);
        return nowruzJdn(year) + daysBeforeMonth(month) + day - 1;
    }

    /** Persian date of a Julian Day Number in {@link #MIN_JDN}..{@link #MAX_JDN}. */
    public static PersianDate fromJdn(long jdn) {
        checkJdn(jdn);
        long year = 1 + Math.floorDiv(33 * (jdn - EPOCH_JDN) + 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);
    }

    /** Persian date of a {@link LocalDate} (proleptic ISO calendar). */
    public static PersianDate fromLocalDate(LocalDate date) {
        long epochDay = date.toEpochDay(); // at most about ±3.7e11, no overflow below
        return fromJdn(epochDay + UNIX_EPOCH_JDN);
    }

    public static LocalDate toLocalDate(int year, int month, int day) {
        return LocalDate.ofEpochDay(toJdn(year, month, day) - UNIX_EPOCH_JDN);
    }

    /** 0 = Saturday (شنبه) ... 6 = Friday (جمعه). */
    public static int dayOfWeek(int year, int month, int day) {
        return (int) Math.floorMod(toJdn(year, month, day) + 2, 7L);
    }

    /** 1 ... 365/366. */
    public static int dayOfYear(int year, int month, int day) {
        checkDate(year, month, day);
        return daysBeforeMonth(month) + day;
    }
}

Tests

PersianCalendarTest.java

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

import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDate;
import java.util.List;

/** Checks PersianCalendar against /data. Run: javac *.java && java PersianCalendarTest */
public class PersianCalendarTest {
    static int checks = 0;

    static void check(boolean ok, Object context) {
        checks++;
        if (!ok) throw new AssertionError("failed: " + context);
    }

    static List<String[]> csv(String name) throws Exception {
        Path path = Path.of(System.getProperty("data", "../../data"), name);
        return Files.readAllLines(path).stream().skip(1).filter(l -> !l.isBlank()).map(l -> l.split(",")).toList();
    }

    public static void main(String[] args) throws Exception {
        for (String[] r : csv("years.csv")) {
            int y = Integer.parseInt(r[0]);
            boolean leap = r[1].equals("1");
            check(PersianCalendar.isLeapYear(y) == leap, "leap " + y);
            check(PersianCalendar.daysInMonth(y, 12) == (leap ? 30 : 29), "esfand " + y);
            check(PersianCalendar.toLocalDate(y, 1, 1).equals(LocalDate.parse(r[3])), "nowruz " + y);
            check(PersianCalendar.toJdn(y, 1, 1) == Long.parseLong(r[4]), "jdn " + y);
            // every day of the year against the ground truth, both directions
            for (int doy = 0; doy < Integer.parseInt(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.parseLong(r[4]) + doy;
                check(PersianCalendar.fromJdn(jdn).equals(new PersianCalendar.PersianDate(y, m, d))
                    && PersianCalendar.toJdn(y, m, d) == jdn, y + "/" + m + "/" + d);
            }
            check(PersianCalendar.dayOfWeek(y, 1, 1) == Integer.parseInt(r[5]), "weekday " + y);
        }
        for (String[] r : csv("test-vectors.csv")) {
            int[] v = new int[8];
            for (int i = 0; i < 8; i++) v[i] = Integer.parseInt(r[i]);
            var p = new PersianCalendar.PersianDate(v[0], v[1], v[2]);
            var g = LocalDate.of(v[3], v[4], v[5]);
            check(PersianCalendar.toLocalDate(v[0], v[1], v[2]).equals(g), p);
            check(PersianCalendar.fromLocalDate(g).equals(p), g);
            check(PersianCalendar.toJdn(v[0], v[1], v[2]) == v[6], p);
            check(PersianCalendar.fromJdn(v[6]).equals(p), p);
            check(PersianCalendar.dayOfWeek(v[0], v[1], v[2]) == v[7], p);
        }
        long first = PersianCalendar.toJdn(PersianCalendar.VERIFIED_MIN_YEAR, 1, 1);
        long last = PersianCalendar.toJdn(PersianCalendar.VERIFIED_MAX_YEAR, 12,
            PersianCalendar.daysInMonth(PersianCalendar.VERIFIED_MAX_YEAR, 12));
        var prev = PersianCalendar.fromJdn(first - 1);
        for (long jdn = first; jdn <= last; jdn++) {
            var d = PersianCalendar.fromJdn(jdn);
            check(PersianCalendar.isValidDate(d.year(), d.month(), d.day()), jdn);
            check(PersianCalendar.toJdn(d.year(), d.month(), d.day()) == jdn, jdn);
            boolean 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(PersianCalendar.toJdn(-1000, 1, 1) == 1582713, "-1000");
        check(PersianCalendar.toJdn(0, 1, 1) == 1947955, "0");
        check(PersianCalendar.toJdn(4000, 1, 1) == 3408925, "4000");
        check(PersianCalendar.fromJdn(0).equals(new PersianCalendar.PersianDate(-5334, 9, 3)), "jdn 0");
        check(PersianCalendar.dayOfWeek(-1000, 1, 1) == 1, "weekday -1000");
        check(PersianCalendar.isLeapYear(-3) && !PersianCalendar.isLeapYear(-1000), "negative leap years");
        for (int[] range : new int[][] {{-1000, 1177}, {3001, 4000}}) {
            long a = PersianCalendar.toJdn(range[0], 1, 1);
            long b = PersianCalendar.toJdn(range[1], 12, PersianCalendar.daysInMonth(range[1], 12));
            var p = PersianCalendar.fromJdn(a - 1);
            for (long jdn = a; jdn <= b; jdn++) {
                var d = PersianCalendar.fromJdn(jdn);
                check(PersianCalendar.isValidDate(d.year(), d.month(), d.day())
                    && PersianCalendar.toJdn(d.year(), d.month(), d.day()) == jdn, jdn);
                boolean 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(PersianCalendar.isValidDate(1403, 12, 30), "1403/12/30");
        check(!PersianCalendar.isValidDate(1404, 12, 30), "1404/12/30");
        check(PersianCalendar.isValidDate(1404, 6, 31), "1404/6/31");
        check(!PersianCalendar.isValidDate(1404, 7, 31), "1404/7/31");
        check(!PersianCalendar.isValidDate(1404, 13, 1), "1404/13/1");
        check(!PersianCalendar.isValidDate(1404, 0, 1), "1404/0/1");
        check(!PersianCalendar.isValidDate(1404, 1, 0), "1404/1/0");
        try {
            PersianCalendar.toJdn(1404, 12, 30);
            check(false, "should throw");
        } catch (IllegalArgumentException expected) {
            checks++;
        }
        check(PersianCalendar.fromLocalDate(LocalDate.of(2025, 3, 21)).equals(new PersianCalendar.PersianDate(1404, 1, 1)), "2025-03-21");
        check(PersianCalendar.fromLocalDate(LocalDate.of(1979, 2, 11)).equals(new PersianCalendar.PersianDate(1357, 11, 22)), "1979-02-11");
        check(PersianCalendar.dayOfYear(1404, 7, 1) == 187, "doy");
        check(PersianCalendar.WEEKDAY_NAMES_EN.get(PersianCalendar.dayOfWeek(1404, 1, 1)).equals("Friday"), "friday");
        // Limits: exact boundaries, and fast rejection of anything outside (no hang, no overflow).
        check(PersianCalendar.toJdn(PersianCalendar.MIN_YEAR, 1, 1) == PersianCalendar.MIN_JDN, "MIN_JDN");
        check(PersianCalendar.toJdn(PersianCalendar.MAX_YEAR, 12, 29) == PersianCalendar.MAX_JDN, "MAX_JDN");
        check(PersianCalendar.fromJdn(PersianCalendar.MIN_JDN).equals(new PersianCalendar.PersianDate(-100_000, 1, 1)), "from MIN_JDN");
        check(PersianCalendar.fromJdn(PersianCalendar.MAX_JDN).equals(new PersianCalendar.PersianDate(100_000, 12, 29)), "from MAX_JDN");
        for (long bad : new long[] {PersianCalendar.MIN_JDN - 1, PersianCalendar.MAX_JDN + 1, Long.MAX_VALUE, Long.MIN_VALUE, 1L << 53}) {
            throwsIllegalArgument(() -> PersianCalendar.fromJdn(bad), "fromJdn " + bad);
        }
        for (int bad : new int[] {PersianCalendar.MIN_YEAR - 1, PersianCalendar.MAX_YEAR + 1, Integer.MAX_VALUE, Integer.MIN_VALUE}) {
            check(!PersianCalendar.isValidDate(bad, 1, 1), "isValidDate " + bad);
            throwsIllegalArgument(() -> PersianCalendar.toJdn(bad, 1, 1), "toJdn " + bad);
            throwsIllegalArgument(() -> PersianCalendar.isLeapYear(bad), "isLeapYear " + bad);
        }
        throwsIllegalArgument(() -> PersianCalendar.fromLocalDate(LocalDate.MAX), "fromLocalDate(MAX)");
        throwsIllegalArgument(() -> PersianCalendar.fromLocalDate(LocalDate.MIN), "fromLocalDate(MIN)");
        try {
            PersianCalendar.MONTH_NAMES_FA.set(0, "X");
            check(false, "MONTH_NAMES_FA must be immutable");
        } catch (UnsupportedOperationException expected) {
            checks++;
        }
        // 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).
        long expected = PersianCalendar.MIN_JDN, leaps = 0, nowruzSum = 0;
        for (int y = PersianCalendar.MIN_YEAR; y <= PersianCalendar.MAX_YEAR; y++) {
            long nowruz = PersianCalendar.toJdn(y, 1, 1);
            int leap = PersianCalendar.isLeapYear(y) ? 1 : 0;
            if (nowruz != expected || !PersianCalendar.fromJdn(nowruz).equals(new PersianCalendar.PersianDate(y, 1, 1))
                    || PersianCalendar.daysInMonth(y, 12) != 29 + leap
                    || !PersianCalendar.fromJdn(nowruz + 364 + leap).equals(new PersianCalendar.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_485 && nowruzSum == 389_592_978_180L, "full-range checksums");
        System.out.println("OK: " + checks + " checks passed");
    }

    static void throwsIllegalArgument(Runnable r, String context) {
        try {
            r.run();
            check(false, context + " should throw");
        } catch (IllegalArgumentException expected) {
            checks++;
        }
    }
}

Other languages