Skip to main content
Contents

Implementation · Dart

Persian (Jalali) calendar in Dart

Dependency-free Dart 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
Dart 3 / Flutter
Tested with
Dart 3.13
Cross-checked against
ICU4C 76.1–79.1 (dart:ffi)
Language-specific checks
Web (JS) integer semantics, dart analyze --fatal-infos
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/dart
    dart pub get && dart test
  3. Call the shared API: function reference

Source

lib/persian_calendar.dart

· 176 lines
Download
// 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 [minYear]..[maxYear] / [minJdn]..[maxJdn] throw [RangeError];
/// invalid dates throw [ArgumentError]. Within that range every intermediate
/// value fits in 32 bits, so results are exact on the web (JavaScript numbers) too.
library;

class PersianDate {
  final int year;

  /// 1 = Farvardin ... 12 = Esfand
  final int month;
  final int day;

  const PersianDate(this.year, this.month, this.day);

  
  bool operator ==(Object other) =>
      other is PersianDate &&
      other.year == year &&
      other.month == month &&
      other.day == day;

  
  int get hashCode => Object.hash(year, month, day);

  
  String toString() => 'PersianDate($year, $month, $day)';
}

/// Years checked against the astronomical calendar.
const int verifiedMinYear = 1178;
const int verifiedMaxYear = 3000;

/// Accepted input range.
const int minYear = -100000;
const int maxYear = 100000;

/// 1 Farvardin -100000 (Gregorian -99379-03-29).
const int minJdn = -34576287;

/// 29 Esfand 100000 (Gregorian 100622-03-13).
const int maxJdn = 38472562;

const int _epochJdn = 1948320;
const int _unixEpochJdn = 2440588; // JDN of 1970-01-01

/// Years the 33-year rule calls leap but are not; the next year is leap instead.
const Set<int> nonLeapCorrection = {
  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,
};

const List<String> monthNamesFa = [
  'فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', //
  'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند',
];
const List<String> monthNamesEn = [
  'Farvardin', 'Ordibehesht', 'Khordad', 'Tir', 'Mordad', //
  'Shahrivar', 'Mehr', 'Aban', 'Azar', 'Dey', 'Bahman', 'Esfand',
];
const List<String> weekdayNamesFa = [
  'شنبه', 'یکشنبه', 'دوشنبه', 'سه‌شنبه', //
  'چهارشنبه', 'پنجشنبه', 'جمعه',
];
const List<String> weekdayNamesEn = [
  'Saturday', 'Sunday', 'Monday', 'Tuesday', //
  'Wednesday', 'Thursday', 'Friday',
];

// Dart's ~/ truncates toward zero; % is already non-negative for b > 0.
int _fdiv(int a, int b) => (a - a % b) ~/ b;

void _checkYear(int year) =>
    RangeError.checkValueInInterval(year, minYear, maxYear, 'year');

void _checkJdn(int jdn) =>
    RangeError.checkValueInInterval(jdn, minJdn, maxJdn, 'jdn');

bool isLeapYear(int year) {
  _checkYear(year);
  if (nonLeapCorrection.contains(year)) return false;
  if (nonLeapCorrection.contains(year - 1)) return true;
  return (25 * year + 11) % 33 < 8;
}

int daysInMonth(int year, int month) {
  _checkYear(year);
  if (month < 1 || month > 12) throw RangeError.range(month, 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.
bool isValidDate(int year, int month, int day) =>
    year >= minYear &&
    year <= maxYear &&
    month >= 1 &&
    month <= 12 &&
    day >= 1 &&
    day <= daysInMonth(year, month);

int _nowruzJdn(int year) {
  var jdn = _epochJdn + 365 * (year - 1) + _fdiv(8 * year + 21, 33);
  if (nonLeapCorrection.contains(year - 1)) jdn -= 1;
  return jdn;
}

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

/// Julian Day Number of a Persian date.
int toJdn(int year, int month, int day) {
  if (!isValidDate(year, month, day)) {
    throw ArgumentError('invalid Persian date: $year/$month/$day');
  }
  return _nowruzJdn(year) + _daysBeforeMonth(month) + day - 1;
}

PersianDate fromJdn(int jdn) {
  _checkJdn(jdn);
  var year = 1 + _fdiv(33 * (jdn - _epochJdn) + 3, 12053);
  while (jdn >= _nowruzJdn(year + 1)) {
    year++;
  }
  while (jdn < _nowruzJdn(year)) {
    year--;
  }
  var doy = jdn - _nowruzJdn(year); // 0-based
  if (doy < 186) return PersianDate(year, doy ~/ 31 + 1, doy % 31 + 1);
  doy -= 186;
  return PersianDate(year, doy ~/ 30 + 7, doy % 30 + 1);
}

/// Persian date of the calendar day of [date] (its own year/month/day fields,
/// so convert with toLocal()/toUtc() first to pick the time zone).
PersianDate fromDateTime(DateTime date) {
  final utcMidnight = DateTime.utc(date.year, date.month, date.day);
  // Exact: midnight UTC is a whole number of days since the epoch.
  return fromJdn(
    utcMidnight.millisecondsSinceEpoch ~/ 86400000 + _unixEpochJdn,
  );
}

/// Midnight UTC of the Persian date's Gregorian day.
DateTime toDateTimeUtc(int year, int month, int day) =>
    DateTime.fromMillisecondsSinceEpoch(
      (toJdn(year, month, day) - _unixEpochJdn) * 86400000,
      isUtc: true,
    );

/// 0 = Saturday (شنبه) ... 6 = Friday (جمعه).
int dayOfWeek(int year, int month, int day) =>
    (toJdn(year, month, day) + 2) % 7;

/// 1 ... 365/366.
int dayOfYear(int year, int month, int day) {
  if (!isValidDate(year, month, day)) {
    throw ArgumentError('invalid Persian date: $year/$month/$day');
  }
  return _daysBeforeMonth(month) + day;
}

Tests

test/persian_calendar_test.dart

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

// Checks the implementation against /data. Run: dart test
import 'dart:io';

import 'package:persian_calendar/persian_calendar.dart';
import 'package:test/test.dart';

List<List<String>> csv(String name) =>
    File('../../data/$name')
        .readAsLinesSync()
        .skip(1)
        .where((l) => l.isNotEmpty)
        .map((l) => l.split(','))
        .toList();

String iso(DateTime d) =>
    '${d.year.toString().padLeft(4, '0')}-'
    '${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')}';

void main() {
  test('years.csv', () {
    for (final r in csv('years.csv')) {
      final y = int.parse(r[0]);
      final leap = r[1] == '1';
      expect(isLeapYear(y), leap, reason: '$y');
      expect(daysInMonth(y, 12), leap ? 30 : 29);
      expect(iso(toDateTimeUtc(y, 1, 1)), r[3]);
      expect(toJdn(y, 1, 1), int.parse(r[4]));
      expect(dayOfWeek(y, 1, 1), int.parse(r[5]));
      // every day of the year against the ground truth, both directions
      for (var doy = 0; doy < int.parse(r[2]); doy++) {
        final m = doy < 186 ? doy ~/ 31 + 1 : (doy - 186) ~/ 30 + 7;
        final d = doy < 186 ? doy % 31 + 1 : (doy - 186) % 30 + 1;
        final jdn = int.parse(r[4]) + doy;
        if (fromJdn(jdn) != PersianDate(y, m, d) || toJdn(y, m, d) != jdn) {
          fail('$y/$m/$d (JDN $jdn)');
        }
      }
    }
  }, testOn: 'vm'); // reads files with dart:io

  test('test-vectors.csv', () {
    for (final r in csv('test-vectors.csv')) {
      final v = r.map(int.parse).toList();
      final p = PersianDate(v[0], v[1], v[2]);
      final g = DateTime.utc(v[3], v[4], v[5]);
      expect(toDateTimeUtc(v[0], v[1], v[2]), g);
      expect(fromDateTime(g), p);
      expect(toJdn(v[0], v[1], v[2]), v[6]);
      expect(fromJdn(v[6]), p);
      expect(dayOfWeek(v[0], v[1], v[2]), v[7]);
    }
  }, testOn: 'vm');

  test('every day 1178..3000 round-trips', () {
    final first = toJdn(verifiedMinYear, 1, 1);
    final last = toJdn(verifiedMaxYear, 12, daysInMonth(verifiedMaxYear, 12));
    var prev = fromJdn(first - 1);
    for (var jdn = first; jdn <= last; jdn++) {
      final d = fromJdn(jdn);
      if (toJdn(d.year, d.month, d.day) != jdn) fail('round trip $jdn');
      final 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)));
      if (!consecutive) fail('not consecutive at $jdn');
      prev = d;
    }
  });

  // Extrapolated years: years <= 0 make intermediate values negative (floor division matters).
  test('extrapolated years', () {
    expect(toJdn(-1000, 1, 1), 1582713);
    expect(toJdn(0, 1, 1), 1947955);
    expect(toJdn(4000, 1, 1), 3408925);
    expect(fromJdn(0), const PersianDate(-5334, 9, 3));
    expect(dayOfWeek(-1000, 1, 1), 1);
    expect(isLeapYear(-3), isTrue);
    expect(isLeapYear(-1000), isFalse);
    for (final r in [
      [-1000, 1177],
      [3001, 4000],
    ]) {
      final first = toJdn(r[0], 1, 1);
      final last = toJdn(r[1], 12, daysInMonth(r[1], 12));
      var prev = fromJdn(first - 1);
      for (var jdn = first; jdn <= last; jdn++) {
        final d = fromJdn(jdn);
        if (toJdn(d.year, d.month, d.day) != jdn) fail('round trip $jdn');
        final 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)));
        if (!consecutive) fail('not consecutive at $jdn');
        prev = d;
      }
    }
  });

  test('validation and known dates', () {
    expect(isValidDate(1403, 12, 30), isTrue);
    expect(isValidDate(1404, 12, 30), isFalse);
    expect(isValidDate(1404, 6, 31), isTrue);
    expect(isValidDate(1404, 7, 31), isFalse);
    expect(isValidDate(1404, 13, 1), isFalse);
    expect(isValidDate(1404, 0, 1), isFalse);
    expect(isValidDate(1404, 1, 0), isFalse);
    expect(() => toJdn(1404, 12, 30), throwsArgumentError);
    expect(
      fromDateTime(DateTime.utc(2025, 3, 21)),
      const PersianDate(1404, 1, 1),
    );
    expect(
      fromDateTime(DateTime.utc(1979, 2, 11)),
      const PersianDate(1357, 11, 22),
    );
    expect(dayOfYear(1404, 7, 1), 187);
    expect(weekdayNamesEn[dayOfWeek(1404, 1, 1)], 'Friday');
  });

  // Limits: exact boundaries; everything outside throws (no overflow, no hang).
  test('limits and bad input', () {
    expect(toJdn(minYear, 1, 1), minJdn);
    expect(toJdn(maxYear, 12, 29), maxJdn);
    expect(fromJdn(minJdn), const PersianDate(minYear, 1, 1));
    expect(fromJdn(maxJdn), const PersianDate(maxYear, 12, 29));
    expect(toDateTimeUtc(minYear, 1, 1), DateTime.utc(-99379, 3, 29));
    expect(toDateTimeUtc(maxYear, 12, 29), DateTime.utc(100622, 3, 13));
    for (final bad in [
      minJdn - 1,
      maxJdn + 1,
      9007199254740992,
      -9007199254740992,
    ]) {
      expect(() => fromJdn(bad), throwsRangeError);
    }
    for (final bad in [minYear - 1, maxYear + 1, 9007199254740992]) {
      expect(isValidDate(bad, 1, 1), isFalse);
      expect(() => toJdn(bad, 1, 1), throwsArgumentError);
      expect(() => isLeapYear(bad), throwsRangeError);
    }
    expect(() => fromDateTime(DateTime.utc(200000, 1, 1)), throwsRangeError);
    expect(() => monthNamesFa[0] = 'X', throwsUnsupportedError);
  });

  // 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).
  test('every year of the full range', () {
    var expected = minJdn, leaps = 0, nowruzSum = 0;
    for (var y = minYear; y <= maxYear; y++) {
      final nowruz = toJdn(y, 1, 1);
      final leap = isLeapYear(y) ? 1 : 0;
      if (nowruz != expected ||
          fromJdn(nowruz) != PersianDate(y, 1, 1) ||
          daysInMonth(y, 12) != 29 + leap ||
          fromJdn(nowruz + 364 + leap) != PersianDate(y, 12, 29 + leap)) {
        fail('year $y');
      }
      leaps += leap;
      nowruzSum += nowruz; // stays below 2^53, so exact on the web too
      expected = nowruz + 365 + leap;
    }
    expect([expected - 1, leaps, nowruzSum], [maxJdn, 48485, 389592978180]);
  });
}

Project files

pubspec.yaml

11 lines
YAMLDownload
name: persian_calendar
description: Solar Hijri (Persian, Jalali, Shamsi) calendar conversions and leap years.
version: 1.0.0
repository: https://github.com/Goudarz/PersianCalendar
publish_to: none

environment:
  sdk: ^3.0.0

dev_dependencies:
  test: ^1.24.0

Other languages