Skip to main content
Contents

Implementation · Go

Persian (Jalali) calendar in Go

Dependency-free Go 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
Go 1.21+
Tested with
Go 1.27
Cross-checked against
ICU4C 76.1–79.1 (purego, no cgo)
Language-specific checks
32-bit int build, FromTime for distant timestamps, go vet
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/go
    go test ./...
  3. Call the shared API: function reference

Source

persiancalendar.go

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

// Package persiancalendar implements the Solar Hijri
// (Persian, Jalali, Shamsi) calendar.
//
// Algorithm: 33-year arithmetic rule + 78-year correction table, the
// same algorithm as ICU 77.1+ and ICU4X. It matches the
// astronomical calendar (52.5 E meridian) for 1178-3000 AP. Months are
// 1-based; weekdays 0 = Saturday ... 6 = Friday.
package persiancalendar

import (
	"fmt"
	"time"
)

// Date is a Persian calendar date.
type Date struct {
	Year  int
	Month int // 1 = Farvardin ... 12 = Esfand
	Day   int
}

const (
	// VerifiedMinYear and VerifiedMaxYear bound the years checked against the astronomical calendar.
	VerifiedMinYear = 1178
	VerifiedMaxYear = 3000

	// MinYear..MaxYear and MinJdn..MaxJdn are the accepted input range. Within it every
	// intermediate value fits in 32 bits, so the package is also safe where int is 32 bits.
	MinYear = -100000
	MaxYear = 100000
	MinJdn  = -34576287 // 1 Farvardin -100000 (Gregorian -99379-03-29)
	MaxJdn  = 38472562  // 29 Esfand 100000 (Gregorian 100622-03-13)

	epochJdn     = 1948320
	unixEpochJdn = 2440588 // JDN of 1970-01-01
)

// Years the 33-year rule calls leap but are not; the next year is leap instead.
var nonLeapCorrection = map[int]bool{}

func init() {
	for _, y := range []int{
		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,
	} {
		nonLeapCorrection[y] = true
	}
}

var (
	monthNamesFa   = [12]string{"فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد", "شهریور", "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند"}
	monthNamesEn   = [12]string{"Farvardin", "Ordibehesht", "Khordad", "Tir", "Mordad", "Shahrivar", "Mehr", "Aban", "Azar", "Dey", "Bahman", "Esfand"}
	weekdayNamesFa = [7]string{"شنبه", "یکشنبه", "دوشنبه", "سه‌شنبه", "چهارشنبه", "پنجشنبه", "جمعه"}
	weekdayNamesEn = [7]string{"Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}
)

// The name tables are returned as array values (copies), so callers cannot change them.

// MonthNamesFa returns the Persian month names; index 0 is Farvardin.
func MonthNamesFa() [12]string { return monthNamesFa }

// MonthNamesEn returns the CLDR English month names; index 0 is Farvardin.
func MonthNamesEn() [12]string { return monthNamesEn }

// WeekdayNamesFa returns the Persian weekday names; index 0 is Saturday.
func WeekdayNamesFa() [7]string { return weekdayNamesFa }

// WeekdayNamesEn returns the English weekday names; index 0 is Saturday.
func WeekdayNamesEn() [7]string { return weekdayNamesEn }

// Go's / and % truncate toward zero; the formulas need floor semantics.
func floorDiv(a, b int) int {
	q := a / b
	if (a%b != 0) && ((a < 0) != (b < 0)) {
		q--
	}
	return q
}

func floorMod(a, b int) int { return a - b*floorDiv(a, b) }

// IsLeapYear reports whether the Persian year has 366 days. It never overflows:
// (25*year + 11) mod 33 is computed from year mod 33.
func IsLeapYear(year int) bool {
	if year >= 1502 && year <= 2988 {
		if nonLeapCorrection[year] {
			return false
		}
		if nonLeapCorrection[year-1] {
			return true
		}
	}
	return floorMod(25*floorMod(year, 33)+11, 33) < 8
}

// DaysInMonth returns 29, 30 or 31. It panics if month is not 1..12 (a programming error;
// use IsValid to check user input).
func DaysInMonth(year, month int) int {
	switch {
	case month < 1 || month > 12:
		panic(fmt.Sprintf("month out of range: %d", month))
	case month <= 6:
		return 31
	case month <= 11:
		return 30
	case IsLeapYear(year):
		return 30
	default:
		return 29
	}
}

// IsValid reports whether year/month/day is a real Persian date in MinYear..MaxYear.
func IsValid(year, month, day int) bool {
	return year >= MinYear && year <= MaxYear && month >= 1 && month <= 12 && day >= 1 && day <= DaysInMonth(year, month)
}

func nowruzJdn(year int) int {
	jdn := epochJdn + 365*(year-1) + floorDiv(8*year+21, 33)
	if nonLeapCorrection[year-1] {
		jdn--
	}
	return jdn
}

func daysBeforeMonth(month int) int {
	if month <= 7 {
		return 31 * (month - 1)
	}
	return 30*(month-1) + 6
}

// ToJdn returns the Julian Day Number of a Persian date.
func ToJdn(year, month, day int) (int, error) {
	if !IsValid(year, month, day) {
		return 0, fmt.Errorf("invalid Persian date: %d/%d/%d", year, month, day)
	}
	return nowruzJdn(year) + daysBeforeMonth(month) + day - 1, nil
}

// FromJdn returns the Persian date of a Julian Day Number in MinJdn..MaxJdn.
func FromJdn(jdn int) (Date, error) {
	if jdn < MinJdn || jdn > MaxJdn {
		return Date{}, fmt.Errorf("jdn out of range [%d, %d]: %d", MinJdn, MaxJdn, jdn)
	}
	year := 1 + floorDiv(33*(jdn-epochJdn)+3, 12053)
	for jdn >= nowruzJdn(year+1) {
		year++
	}
	for jdn < nowruzJdn(year) {
		year--
	}
	doy := jdn - nowruzJdn(year) // 0-based
	if doy < 186 {
		return Date{year, doy/31 + 1, doy%31 + 1}, nil
	}
	doy -= 186
	return Date{year, doy/30 + 7, doy%30 + 1}, nil
}

// FromTime returns the Persian date of t in t's own location.
// Use t.In(loc) first to choose the time zone (e.g. Asia/Tehran).
func FromTime(t time.Time) (Date, error) {
	y, m, d := t.Date()
	civil := time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
	jdn := civil.Unix()/86400 + unixEpochJdn // int64: checked before converting to int
	if jdn < MinJdn || jdn > MaxJdn {
		return Date{}, fmt.Errorf("date out of range: %s", civil.Format("2006-01-02"))
	}
	return FromJdn(int(jdn))
}

// ToTime returns midnight of the Persian date in loc.
func ToTime(year, month, day int, loc *time.Location) (time.Time, error) {
	jdn, err := ToJdn(year, month, day)
	if err != nil {
		return time.Time{}, err
	}
	g := time.Unix(int64(jdn-unixEpochJdn)*86400, 0).UTC()
	return time.Date(g.Year(), g.Month(), g.Day(), 0, 0, 0, 0, loc), nil
}

// Weekday returns 0 = Saturday (شنبه) ... 6 = Friday (جمعه).
func Weekday(year, month, day int) (int, error) {
	jdn, err := ToJdn(year, month, day)
	if err != nil {
		return 0, err
	}
	return floorMod(jdn+2, 7), nil
}

// DayOfYear returns 1 ... 365/366.
func DayOfYear(year, month, day int) (int, error) {
	if !IsValid(year, month, day) {
		return 0, fmt.Errorf("invalid Persian date: %d/%d/%d", year, month, day)
	}
	return daysBeforeMonth(month) + day, nil
}

Tests

persiancalendar_test.go

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

package persiancalendar

import (
	"math"
	"os"
	"strconv"
	"strings"
	"testing"
	"time"
)

func csv(t *testing.T, name string) [][]string {
	b, err := os.ReadFile("../../data/" + name)
	if err != nil {
		t.Fatal(err)
	}
	var rows [][]string
	for _, l := range strings.Split(strings.TrimSpace(string(b)), "\n")[1:] {
		rows = append(rows, strings.Split(l, ","))
	}
	return rows
}

func atoi(s string) int { n, _ := strconv.Atoi(s); return n }

func must(v int, err error) int {
	if err != nil {
		panic(err)
	}
	return v
}

// fj and ft unwrap FromJdn / FromTime for inputs that are known to be valid.
func fj(jdn int) Date      { return mustDate(FromJdn(jdn)) }
func ft(tm time.Time) Date { return mustDate(FromTime(tm)) }

func mustDate(d Date, err error) Date {
	if err != nil {
		panic(err)
	}
	return d
}

// Limits: exact boundaries, and fast rejection of anything outside (no hang, no overflow).
func TestLimits(t *testing.T) {
	if must(ToJdn(MinYear, 1, 1)) != MinJdn || must(ToJdn(MaxYear, 12, 29)) != MaxJdn {
		t.Fatal("limits")
	}
	if mustDate(FromJdn(MinJdn)) != (Date{MinYear, 1, 1}) || mustDate(FromJdn(MaxJdn)) != (Date{MaxYear, 12, 29}) {
		t.Fatal("limit dates")
	}
	for _, bad := range []int{MinJdn - 1, MaxJdn + 1, math.MaxInt, math.MinInt, math.MaxInt / 2} {
		if _, err := FromJdn(bad); err == nil {
			t.Fatalf("FromJdn(%d) should fail", bad)
		}
	}
	for _, bad := range []int{MinYear - 1, MaxYear + 1, math.MaxInt, math.MinInt} {
		if IsValid(bad, 1, 1) {
			t.Fatalf("IsValid(%d)", bad)
		}
		if _, err := ToJdn(bad, 1, 1); err == nil {
			t.Fatalf("ToJdn(%d) should fail", bad)
		}
		_ = IsLeapYear(bad) // must not panic or overflow
	}
	if IsLeapYear(math.MaxInt) != IsLeapYear(math.MaxInt%33+33*1000) {
		t.Fatal("IsLeapYear must reduce mod 33 without overflow")
	}
	for _, far := range []time.Time{time.Date(math.MaxInt32, 1, 1, 0, 0, 0, 0, time.UTC), time.Date(math.MinInt32, 1, 1, 0, 0, 0, 0, time.UTC)} {
		if _, err := FromTime(far); err == nil {
			t.Fatalf("FromTime(%v) should fail", far)
		}
	}
	names := MonthNamesFa()
	names[0] = "X"
	if MonthNamesFa()[0] != "فروردین" {
		t.Fatal("name tables must not be shared")
	}
}

func TestYears(t *testing.T) {
	for _, r := range csv(t, "years.csv") {
		y, leap := atoi(r[0]), r[1] == "1"
		if IsLeapYear(y) != leap {
			t.Fatalf("leap %d", y)
		}
		g, _ := ToTime(y, 1, 1, time.UTC)
		if g.Format("2006-01-02") != r[3] {
			t.Fatalf("nowruz %d: %s != %s", y, g.Format("2006-01-02"), r[3])
		}
		if must(ToJdn(y, 1, 1)) != atoi(r[4]) || must(Weekday(y, 1, 1)) != atoi(r[5]) {
			t.Fatalf("jdn/weekday %d", y)
		}
		// every day of the year against the ground truth, both directions
		for doy := 0; doy < atoi(r[2]); doy++ {
			m, d := doy/31+1, doy%31+1
			if doy >= 186 {
				m, d = (doy-186)/30+7, (doy-186)%30+1
			}
			jdn := atoi(r[4]) + doy
			if fj(jdn) != (Date{y, m, d}) || must(ToJdn(y, m, d)) != jdn {
				t.Fatalf("%d/%d/%d (JDN %d)", y, m, d, jdn)
			}
		}
	}
}

func TestVectors(t *testing.T) {
	for _, r := range csv(t, "test-vectors.csv") {
		p := Date{atoi(r[0]), atoi(r[1]), atoi(r[2])}
		g := time.Date(atoi(r[3]), time.Month(atoi(r[4])), atoi(r[5]), 0, 0, 0, 0, time.UTC)
		if ft(g) != p {
			t.Fatalf("FromTime %v", g)
		}
		if tt, _ := ToTime(p.Year, p.Month, p.Day, time.UTC); !tt.Equal(g) {
			t.Fatalf("ToTime %v", p)
		}
		if must(ToJdn(p.Year, p.Month, p.Day)) != atoi(r[6]) || fj(atoi(r[6])) != p {
			t.Fatalf("jdn %v", p)
		}
		if must(Weekday(p.Year, p.Month, p.Day)) != atoi(r[7]) {
			t.Fatalf("weekday %v", p)
		}
	}
}

func TestEveryDay(t *testing.T) {
	first := must(ToJdn(VerifiedMinYear, 1, 1))
	last := must(ToJdn(VerifiedMaxYear, 12, DaysInMonth(VerifiedMaxYear, 12)))
	prev := fj(first - 1)
	for jdn := first; jdn <= last; jdn++ {
		d := fj(jdn)
		if !IsValid(d.Year, d.Month, d.Day) || must(ToJdn(d.Year, d.Month, d.Day)) != jdn {
			t.Fatalf("round trip %d", jdn)
		}
		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 {
			t.Fatalf("not consecutive at %d", jdn)
		}
		prev = d
	}
}

// Extrapolated years: years <= 0 make intermediate values negative (floor division matters).
func TestExtrapolatedYears(t *testing.T) {
	if must(ToJdn(-1000, 1, 1)) != 1582713 || must(ToJdn(0, 1, 1)) != 1947955 || must(ToJdn(4000, 1, 1)) != 3408925 {
		t.Fatal("fixed values")
	}
	if fj(0) != (Date{-5334, 9, 3}) || must(Weekday(-1000, 1, 1)) != 1 || !IsLeapYear(-3) || IsLeapYear(-1000) {
		t.Fatal("fixed values")
	}
	for _, r := range [][2]int{{-1000, 1177}, {3001, 4000}} {
		first := must(ToJdn(r[0], 1, 1))
		last := must(ToJdn(r[1], 12, DaysInMonth(r[1], 12)))
		prev := fj(first - 1)
		for jdn := first; jdn <= last; jdn++ {
			d := fj(jdn)
			if !IsValid(d.Year, d.Month, d.Day) || must(ToJdn(d.Year, d.Month, d.Day)) != jdn {
				t.Fatalf("round trip %d", jdn)
			}
			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 {
				t.Fatalf("not consecutive at %d", jdn)
			}
			prev = d
		}
	}
}

func TestValidationAndKnownDates(t *testing.T) {
	cases := []struct {
		y, m, d int
		ok      bool
	}{{1403, 12, 30, true}, {1404, 12, 30, false}, {1404, 6, 31, true}, {1404, 7, 31, false},
		{1404, 13, 1, false}, {1404, 0, 1, false}, {1404, 1, 0, false}}
	for _, c := range cases {
		if IsValid(c.y, c.m, c.d) != c.ok {
			t.Fatalf("IsValid %v", c)
		}
	}
	if _, err := ToJdn(1404, 12, 30); err == nil {
		t.Fatal("expected error")
	}
	if ft(time.Date(2025, 3, 21, 0, 0, 0, 0, time.UTC)) != (Date{1404, 1, 1}) {
		t.Fatal("2025-03-21")
	}
	if ft(time.Date(1979, 2, 11, 0, 0, 0, 0, time.UTC)) != (Date{1357, 11, 22}) {
		t.Fatal("1979-02-11")
	}
	// Time zone matters: 2025-03-20T21:00Z is 1 Farvardin in Tehran, 30 Esfand in UTC.
	instant := time.Date(2025, 3, 20, 21, 0, 0, 0, time.UTC)
	if tehran, err := time.LoadLocation("Asia/Tehran"); err == nil {
		if ft(instant.In(tehran)) != (Date{1404, 1, 1}) {
			t.Fatal("Tehran time zone")
		}
	}
	if ft(instant) != (Date{1403, 12, 30}) {
		t.Fatal("UTC")
	}
	if WeekdayNamesEn()[must(Weekday(1404, 1, 1))] != "Friday" || must(DayOfYear(1404, 7, 1)) != 187 {
		t.Fatal("weekday/day of year")
	}
}

// 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). int64 sums:
// the Nowruz sum does not fit in a 32-bit int.
func TestEveryYearOfTheFullRange(t *testing.T) {
	expected := MinJdn
	var leaps, nowruzSum int64
	for y := MinYear; y <= MaxYear; y++ {
		nowruz := must(ToJdn(y, 1, 1))
		leap := 0
		if IsLeapYear(y) {
			leap = 1
		}
		if nowruz != expected || fj(nowruz) != (Date{y, 1, 1}) || DaysInMonth(y, 12) != 29+leap ||
			fj(nowruz+364+leap) != (Date{y, 12, 29 + leap}) {
			t.Fatalf("year %d", y)
		}
		leaps += int64(leap)
		nowruzSum += int64(nowruz)
		expected = nowruz + 365 + leap
	}
	if expected-1 != MaxJdn || leaps != 48485 || nowruzSum != 389592978180 {
		t.Fatalf("checksums: last %d, leaps %d, sum %d", expected-1, leaps, nowruzSum)
	}
}

Project files

go.mod

3 lines
go.modDownload
module github.com/Goudarz/PersianCalendar/implementations/go

go 1.21

Other languages