ptime

package module
v1.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 11, 2026 License: MIT Imports: 9 Imported by: 0

README

Go Persian Calendar

A complete, dependency-free Persian (Solar Hijri / Jalali) calendar for Go — shaped like the standard time package.

Go Reference CI Go Report Card Go Version

English · فارسی


ptime converts between the Persian and Gregorian calendars and gives you a Time type that behaves like time.Time: same method names, same value semantics, same layout-driven formatting. Conversions go through the Julian Day Number, so they stay exact on both sides of the 1582 Gregorian reform.

Features

  • Familiar API — Now, Date, Unix, Add, AddDate, Sub, Before, After, Equal, Compare, Truncate, Round.
  • Two layout languages — the pattern-letter style (yyyy/MM/dd) and the standard library reference-time style (2006/01/02).
  • Parsing, not just formatting — Parse, ParseInLocation, ParseTimeFormat, ParseTimeFormatInLocation.
  • Ready for JSON and SQL — implements json.Marshaler, encoding.TextMarshaler, driver.Valuer and sql.Scanner.
  • Iranian and Dari names — Dari month names are selected automatically for the Asia/Kabul location.
  • Calendar helpers — leap years, week of month, week of year, first and last day of the week, month and year.
  • Public holidays — the optional holiday package answers whether a date is a day off, and says so honestly when a lunar date is still an estimate.
  • Zero dependencies, allocation-conscious formatting, and a fuzz-tested parser.

Installation

go get github.com/amiranmanesh/go-persian-calendar

Requires Go 1.21 or newer.

import ptime "github.com/amiranmanesh/go-persian-calendar"

Quick start

Gregorian to Persian
gt := time.Date(2016, time.January, 1, 12, 1, 1, 0, ptime.Iran())

pt := ptime.New(gt)

fmt.Println(pt.Date()) // 1394 دی 11
Persian to Gregorian
pt := ptime.Date(1394, ptime.Mehr, 2, 12, 59, 59, 0, ptime.Iran())

fmt.Println(pt.Time().Format(time.DateOnly)) // 2015-09-24
The current moment
pt := ptime.Now()

fmt.Println(pt.Date())                                  // 1394 بهمن 11
fmt.Println(pt.Clock())                                 // 21 54 30
fmt.Println(pt.Unix())                                  // 1454277270
fmt.Println(pt.Weekday())                               // یک‌شنبه
fmt.Println(pt.Yesterday().Weekday())                   // شنبه
fmt.Println(pt.BeginningOfMonth().Format(ptime.DateOnly)) // 1394-11-01
fmt.Println(pt.LastMonthDay().Day())                    // 30
fmt.Println(pt.IsLeap(), pt.YearWeek(), pt.MonthWeek())
Formatting
pt := ptime.Unix(1454277270, 0)

pt.Format("yyyy/MM/dd E hh:mm:ss a") // 1394/11/11 یک‌شنبه 09:54:30 ب.ظ
pt.Format(ptime.RFC3339)             // 1394-11-11T21:54:30+03:30
pt.Format(ptime.LongDate)            // یک‌شنبه 11 بهمن 1394
pt.TimeFormat("2 Jan 2006")          // 11 بهمن 1394

Formatting into an existing buffer avoids the string allocation:

buf = pt.AppendFormat(buf[:0], ptime.DateTime)
Parsing
pt, err := ptime.Parse(ptime.DateTime, "1394-07-02 12:59:59")
if err != nil {
    // *ptime.ParseError reports which layout element failed and where
}

pt, err = ptime.ParseInLocation("d MMM yyyy", "2 مهر 1394", ptime.Iran())
pt, err = ptime.ParseTimeFormat("2006/01/02", "1394/07/02")

Without a time zone in the value, Parse returns a time in UTC — use ParseInLocation to pick a different default.

JSON
type Event struct {
    Name string     `json:"name"`
    At   ptime.Time `json:"at"`
}

json.Marshal(Event{
    Name: "نوروز",
    At:   ptime.Date(1404, ptime.Farvardin, 1, 0, 0, 0, 0, ptime.Iran()),
})
// {"name":"نوروز","at":"1404-01-01T00:00:00+03:30"}

The zero Time marshals to null and back.

SQL
var at ptime.Time

// Value() stores a Gregorian timestamp, Scan() reads one back.
db.QueryRow("SELECT created_at FROM events WHERE id = $1", id).Scan(&at)
db.Exec("INSERT INTO events (created_at) VALUES ($1)", at)

Public holidays

import "github.com/amiranmanesh/go-persian-calendar/holiday"

cal := holiday.Iran()

cal.IsHoliday(pt)                 // is this a day off, Fridays included?
cal.Lookup(pt).Title()            // "روز طبیعت، سیزده به‌در"
cal.NextWorkday(pt)               // the next working day
cal.Workdays(from, to)            // working days in a range
cal.Holidays(1404)                // every day off in a year

Iranian holidays come in three kinds, and the package treats each one honestly:

Kind Example How it is resolved Confidence
Fixed in the Persian calendar Nowruz, 22 Bahman a rule in code, set by law always Confirmed
Fixed in the Hijri calendar Eid al-Fitr, Ashura computed through the tabular Hijri calendar Estimated until the year is settled
One-off an air pollution closure data only Confirmed

Iran fixes lunar dates by moon sighting, which no algorithm can predict: the arithmetic calendar disagrees with the announced date about 43% of the time, almost always by a single day. So a lunar occurrence is reported as Estimated until its year has passed and the announced date is recorded:

for _, event := range cal.Lookup(pt).Events {
    if event.Confidence == holiday.Estimated {
        // Do not settle payroll on this date yet.
    }
}

cal.ConfirmedThrough() // the last year whose lunar dates are settled

The data is embedded at build time, so the package does no I/O and works offline. go get -u brings newer data. A service that must pick up a correction without rebuilding can load a fresher copy of the same file:

resp, err := http.Get("https://amiranmanesh.github.io/go-persian-calendar/data/v1/iran.json")
// ...
overrides, err := holiday.Load(resp.Body)
cal = holiday.Iran().WithOverrides(overrides)

A monthly workflow reconciles the computed calendar against published Iranian calendars and opens a pull request when a date moves, so every change to the data is reviewed rather than applied silently.

Predefined layouts

Constant Layout Example
RFC3339 yyyy-MM-ddTHH:mm:ssZ 1394-07-02T12:59:59+03:30
RFC3339Nano yyyy-MM-ddTHH:mm:ss.999999999Z 1394-07-02T12:59:59.05206509+03:30
DateTime yyyy-MM-dd HH:mm:ss 1394-07-02 12:59:59
DateOnly yyyy-MM-dd 1394-07-02
TimeOnly HH:mm:ss 12:59:59
Kitchen h:mm a 12:59 ب.ظ
LongDate E d MMM yyyy پنج‌شنبه 2 مهر 1394

Layout reference

Format and Parse — pattern letters
Pattern Meaning Example
yyyy, yyy, y year 1394
yy 2-digit year 94
MMM Persian month name فروردین
MMI Dari month name حمل
MM 2-digit month 01
M month 1
dd 2-digit day of month 01
d day of month 1
E Persian weekday name شنبه
e short weekday name ش
A 12-hour marker قبل از ظهر
a short 12-hour marker ق.ظ
HH / H hour [00-23] / [0-23] 09 / 9
kk / k hour [01-24] / [1-24] 09 / 9
hh / h hour [01-12] / [1-12] 09 / 9
KK / K hour [00-11] / [0-11] 09 / 9
mm / m minute 05 / 5
ss / s second 05 / 5
n part of the day صبح
ns nanosecond, as a plain number 52065090
S 3-digit millisecond 052
.000 … .000000000 fractional second, fixed width .052
.999 … .999999999 fractional second, trailing zeros removed .052
D / RD day of year / remaining days of year 186
w / rw week of year / remaining weeks of year 46
W / rd week of month / remaining days of month 3
z time zone name Asia/Tehran
Z time zone offset +03:30

Anything else is copied verbatim. Computed fields (D, RD, w, rw, W, rd, E, e, n) are matched and discarded when parsing.

TimeFormat and ParseTimeFormat — reference time
Layout Meaning Example
2006 / 06 year 1394 / 94
01 / 1 month 07 / 7
Jan, January month name مهر
02 / 2 / _2 day of month 07 / 7 / " 7"
Mon / Monday weekday ش / شنبه
Morning part of the day صبح
15 hour [00-23] 14
03 / 3 hour [01-12] 02 / 2
04 / 4 minute 07 / 7
05 / 5 second 08 / 8
.000 … .999999999 fractional second .052
PM / pm 12-hour marker بعد از ظهر / ب.ظ
MST time zone name Asia/Tehran
-0700, -07, -07:00, Z0700, Z07:00 time zone offset +0330

Locations

ptime.Iran() and ptime.Afghanistan() return Asia/Tehran and Asia/Kabul. Both are cached after the first lookup and fall back to a fixed offset when the host has no time zone database.

Month names follow the location: TimeFormat renders Dari names (میزان) in Asia/Kabul and Iranian names (مهر) everywhere else. Format chooses explicitly, with MMM for Iranian and MMI for Dari.

Limitations

  • The oldest representable Gregorian year is 1097; New returns the zero Time for anything older.
  • Leap years use the arithmetic 33-year cycle rule, which matches the official Iranian calendar over the range the package targets.

Development

make test     # go test ./... -race -cover
make lint     # golangci-lint
make bench    # benchmarks
make fuzz     # a short fuzzing pass over the parser
make cover    # HTML coverage report

Documentation

Full API documentation lives on pkg.go.dev. Longer guides are in the wiki.

Contributing

Issues and pull requests are welcome — see CONTRIBUTING.md.

Credits

Originally created by Navid Fathollahzade as yaa110/go-persian-calendar, and maintained here with a modernized API, a parser, encoding support and a reworked toolchain.

License

MIT — see LICENSE.

Documentation

Overview

Package ptime provides a complete implementation of the Persian (Solar Hijri / Jalali) calendar, designed to mirror the standard library time package as closely as possible.

Overview

The central type is Time, an immutable value describing a moment in the Persian calendar together with its time.Location. Conversions between the Persian and Gregorian calendars go through the Julian Day Number, which keeps them exact for both the Julian and the Gregorian era.

pt := ptime.Date(1394, ptime.Mehr, 2, 12, 59, 59, 0, ptime.Iran())
fmt.Println(pt.Time().Format(time.DateOnly)) // 2015-09-24

Creating a Time

Use Now for the current moment, Date to build one from Persian calendar components, New to convert an existing time.Time, Unix to convert a Unix timestamp, or Parse to read one from text.

Formatting and parsing

Two layout languages are supported:

  • The ptime layout language used by Time.Format and Parse, built from repeated pattern letters such as "yyyy/MM/dd HH:mm:ss".
  • The standard library reference-time language used by Time.TimeFormat and ParseTimeFormat, such as "2006/01/02 15:04:05".

Predefined layouts such as RFC3339, DateTime and DateOnly cover the common cases.

Encoding

Time implements encoding.TextMarshaler, encoding.TextUnmarshaler, [json.Marshaler], [json.Unmarshaler], driver.Valuer and [sql.Scanner], so it can be stored in JSON documents and SQL databases without a wrapper type.

Localization

Both Iranian and Dari month names are available. Time.TimeFormat picks the Dari names automatically when the location is Afghanistan.

Limitations

Gregorian years below 1097 are not representable; New returns the zero Time for them.

Index

Examples

Constants

View Source
const (
	// RFC3339 is the RFC 3339 profile of ISO 8601, e.g. "1394-07-02T12:59:59+03:30".
	RFC3339 = "yyyy-MM-ddTHH:mm:ssZ"
	// RFC3339Nano is RFC3339 with a fractional second, trailing zeros removed.
	RFC3339Nano = "yyyy-MM-ddTHH:mm:ss.999999999Z"
	// DateTime is a date and a clock reading, e.g. "1394-07-02 12:59:59".
	DateTime = "yyyy-MM-dd HH:mm:ss"
	// DateOnly is a date without a clock reading, e.g. "1394-07-02".
	DateOnly = "yyyy-MM-dd"
	// TimeOnly is a clock reading without a date, e.g. "12:59:59".
	TimeOnly = "HH:mm:ss"
	// Kitchen is a short 12-hour clock reading, e.g. "12:59 ب.ظ".
	Kitchen = "h:mm a"
	// LongDate spells out the weekday and month, e.g. "پنج‌شنبه 2 مهر 1394".
	LongDate = "E d MMM yyyy"
)

Predefined layouts for use with Time.Format and Parse.

Variables

View Source
var ErrScanSource = errors.New("ptime: unsupported source type for Scan")

ErrScanSource is returned by Time.Scan when the database driver hands over a value that cannot be converted into a Time.

Functions

func Afghanistan

func Afghanistan() *time.Location

Afghanistan returns the "Asia/Kabul" time zone.

If the time zone database is unavailable, a fixed UTC+04:30 zone is returned instead. The result is cached, so calling Afghanistan repeatedly is cheap.

func Iran

func Iran() *time.Location

Iran returns the "Asia/Tehran" time zone.

If the time zone database is unavailable, a fixed UTC+03:30 zone is returned instead. The result is cached, so calling Iran repeatedly is cheap.

Types

type AmPm

type AmPm int

An AmPm specifies the 12-hour clock marker.

const (
	Am AmPm = iota
	Pm
)

The 12-hour clock markers.

func (AmPm) Short

func (a AmPm) Short() string

Short returns the abbreviated Persian name of the 12-hour marker.

func (AmPm) String

func (a AmPm) String() string

String returns the Persian name of the 12-hour marker.

type DayTime

type DayTime int

A DayTime represents a part of the day, derived from the hour.

const (
	Midnight DayTime = iota
	Dawn
	Morning
	BeforeNoon
	Noon
	AfterNoon
	Evening
	Night
)

Parts of the day, each covering a three hour window.

func (DayTime) String

func (d DayTime) String() string

String returns the Persian name of the part of the day. Out of range values are clamped to Midnight and Night.

type Month

type Month int

A Month specifies a month of the year, starting from Farvardin = 1.

const (
	Farvardin Month = 1 + iota
	Ordibehesht
	Khordad
	Tir
	Mordad
	Shahrivar
	Mehr
	Aban
	Azar
	Dey
	Bahman
	Esfand
)

Months of the Persian calendar, as used in Iran.

const (
	Hamal Month = 1 + iota
	Sur
	Jauza
	Saratan
	Asad
	Sonboleh
	Mizan
	Aqrab
	Qos
	Jady
	Dolv
	Hut
)

Months of the Persian calendar, as used in Afghanistan (Dari names). They are aliases of the Iranian names above and share the same values.

func (Month) Dari

func (m Month) Dari() string

Dari returns the Dari (Afghan Persian) name of the month. Out of range values are clamped to Hamal and Hut.

Example
package main

import (
	"fmt"

	ptime "github.com/amiranmanesh/go-persian-calendar"
)

func main() {
	fmt.Println(ptime.Mehr.String(), ptime.Mehr.Dari())
}
Output:
مهر میزان

func (Month) IsValid

func (m Month) IsValid() bool

IsValid reports whether m is in the range [Farvardin, Esfand].

func (Month) String

func (m Month) String() string

String returns the Iranian Persian name of the month. Out of range values are clamped to Farvardin and Esfand.

type ParseError

type ParseError struct {
	// Layout is the layout that was given to the parse function.
	Layout string
	// Value is the value that was given to the parse function.
	Value string
	// LayoutElem is the layout element that failed to match.
	LayoutElem string
	// ValueElem is the remainder of the value at the point of failure.
	ValueElem string
	// Message describes the failure when it is not a plain mismatch.
	Message string
}

A ParseError describes a problem parsing a time string.

func (*ParseError) Error

func (e *ParseError) Error() string

Error implements the error interface.

type Time

type Time struct {
	// contains filtered or unexported fields
}

A Time represents an instant in the Persian (Solar Hijri) calendar with nanosecond precision.

The zero value is reported by Time.IsZero. Like time.Time, a Time is small enough to pass by value; every method with a value receiver returns a new Time instead of mutating the receiver.

func Date

func Date(year int, month Month, day, hour, minute, sec, nsec int, loc *time.Location) Time

Date returns the Time corresponding to the given Persian calendar date and clock reading.

The arguments may be outside their usual ranges and are normalized during the conversion. If loc is nil, the local time zone is used.

Example
package main

import (
	"fmt"
	"time"

	ptime "github.com/amiranmanesh/go-persian-calendar"
)

func main() {
	pt := ptime.Date(1394, ptime.Mehr, 2, 12, 59, 59, 0, ptime.Iran())

	fmt.Println(pt.Time().Format(time.DateOnly))
}
Output:
2015-09-24

func New

func New(t time.Time) Time

New converts a Gregorian time into the Persian calendar.

It returns the zero Time if the Gregorian year of t is below 1097.

Example
package main

import (
	"fmt"
	"time"

	ptime "github.com/amiranmanesh/go-persian-calendar"
)

func main() {
	gt := time.Date(2016, time.January, 1, 12, 1, 1, 0, ptime.Iran())

	pt := ptime.New(gt)

	fmt.Println(pt.Date())
}
Output:
1394 دی 11

func Now

func Now() Time

Now returns the current time in the Persian calendar and the local time zone.

func Parse

func Parse(layout, value string) (Time, error)

Parse parses a formatted Persian date string using the layout language of Time.Format.

Fields absent from the layout default to Farvardin 1 of year 1 at 00:00:00. Computed fields such as the day of year or the week of month are matched and discarded, since they carry no information the other fields do not.

In the absence of a time zone in the value, Parse returns a time in UTC. Use ParseInLocation to pick a different default.

Example
package main

import (
	"fmt"

	ptime "github.com/amiranmanesh/go-persian-calendar"
)

func main() {
	pt, err := ptime.Parse("yyyy/MM/dd HH:mm:ss", "1394/07/02 12:59:59")
	if err != nil {
		panic(err)
	}

	fmt.Println(pt.Format(ptime.LongDate))
}
Output:
پنج‌شنبه 2 مهر 1394

func ParseInLocation

func ParseInLocation(layout, value string, loc *time.Location) (Time, error)

ParseInLocation is like Parse but interprets a value without a time zone as being in the given location.

Example
package main

import (
	"fmt"

	ptime "github.com/amiranmanesh/go-persian-calendar"
)

func main() {
	pt, err := ptime.ParseInLocation(ptime.DateOnly, "1403-12-30", ptime.Iran())
	if err != nil {
		panic(err)
	}

	fmt.Println(pt.IsLeap(), pt.Format(ptime.RFC3339))
}
Output:
true 1403-12-30T00:00:00+03:30

func ParseTimeFormat

func ParseTimeFormat(layout, value string) (Time, error)

ParseTimeFormat parses a formatted Persian date string using the standard library reference-time layout language of Time.TimeFormat.

In the absence of a time zone in the value, ParseTimeFormat returns a time in UTC. Use ParseTimeFormatInLocation to pick a different default.

func ParseTimeFormatInLocation

func ParseTimeFormatInLocation(layout, value string, loc *time.Location) (Time, error)

ParseTimeFormatInLocation is like ParseTimeFormat but interprets a value without a time zone as being in the given location.

func Unix

func Unix(sec, nsec int64) Time

Unix returns the Time corresponding to the given Unix time: sec seconds and nsec nanoseconds since January 1, 1970 UTC.

func UnixMicro

func UnixMicro(usec int64) Time

UnixMicro returns the Time corresponding to the given Unix time: usec microseconds since January 1, 1970 UTC.

func UnixMilli

func UnixMilli(msec int64) Time

UnixMilli returns the Time corresponding to the given Unix time: msec milliseconds since January 1, 1970 UTC.

func (Time) Add

func (t Time) Add(d time.Duration) Time

Add returns t+d.

func (Time) AddDate

func (t Time) AddDate(years, months, days int) Time

AddDate returns the time corresponding to adding the given number of years, months and days to t. The result is normalized the same way Time.Set is.

Example
package main

import (
	"fmt"

	ptime "github.com/amiranmanesh/go-persian-calendar"
)

func main() {
	pt := ptime.Date(1394, ptime.Esfand, 29, 0, 0, 0, 0, ptime.Iran())

	fmt.Println(pt.AddDate(0, 0, 1).Format(ptime.DateOnly))
}
Output:
1395-01-01

func (Time) After

func (t Time) After(u Time) bool

After reports whether t is after u.

func (Time) AmPm

func (t Time) AmPm() AmPm

AmPm returns the 12-hour clock marker of t.

func (Time) AppendFormat

func (t Time) AppendFormat(b []byte, layout string) []byte

AppendFormat is like Time.Format but appends the result to b and returns the extended buffer, avoiding a string allocation.

func (Time) AppendTimeFormat

func (t Time) AppendTimeFormat(b []byte, layout string) []byte

AppendTimeFormat is like Time.TimeFormat but appends the result to b and returns the extended buffer.

func (*Time) At

func (t *Time) At(hour, minute, sec, nsec int)

At sets the clock reading of t.

func (Time) Before

func (t Time) Before(u Time) bool

Before reports whether t is before u.

func (Time) BeginningOfMonth

func (t Time) BeginningOfMonth() Time

BeginningOfMonth returns the first day of the month of t at 00:00:00.

Example
package main

import (
	"fmt"

	ptime "github.com/amiranmanesh/go-persian-calendar"
)

func main() {
	pt := ptime.Date(1394, ptime.Mehr, 17, 13, 45, 12, 0, ptime.Iran())

	fmt.Println(pt.BeginningOfMonth().Format(ptime.DateTime))
	fmt.Println(pt.LastMonthDay().Format(ptime.DateOnly))
}
Output:
1394-07-01 00:00:00
1394-07-30

func (Time) BeginningOfWeek

func (t Time) BeginningOfWeek() Time

BeginningOfWeek returns the first day of the week of t at 00:00:00.

func (Time) BeginningOfYear

func (t Time) BeginningOfYear() Time

BeginningOfYear returns the first day of the year of t at 00:00:00.

func (Time) Clock

func (t Time) Clock() (int, int, int)

Clock returns the hour, minute and second of t.

func (Time) Compare

func (t Time) Compare(u Time) int

Compare compares t with u: it returns -1 if t is before u, +1 if t is after u, and 0 if they represent the same instant.

func (Time) Date

func (t Time) Date() (int, Month, int)

Date returns the year, month and day of month of t.

func (Time) Day

func (t Time) Day() int

Day returns the day of month of t.

func (Time) DayTime

func (t Time) DayTime() DayTime

DayTime returns the part of the day t falls into:

[0,3)   midnight
[3,6)   dawn
[6,9)   morning
[9,12)  before noon
[12,15) noon
[15,18) afternoon
[18,21) evening
[21,24) night

func (Time) Equal

func (t Time) Equal(u Time) bool

Equal reports whether t and u represent the same instant.

Two times can be equal even if they are in different locations: 6:00 +0200 and 4:00 UTC are equal.

func (Time) FirstMonthDay

func (t Time) FirstMonthDay() Time

FirstMonthDay returns the first day of the month of t, keeping the clock of t.

func (Time) FirstWeekDay

func (t Time) FirstWeekDay() Time

FirstWeekDay returns the first day of the week of t, keeping the clock of t.

func (Time) FirstYearDay

func (t Time) FirstYearDay() Time

FirstYearDay returns the first day of the year of t, keeping the clock of t.

func (Time) Format

func (t Time) Format(layout string) string

Format returns the textual representation of t according to layout.

The layout is built from the following pattern letters. Anything else is copied to the output verbatim.

yyyy, yyy, y  year (e.g. 1394)
yy            2-digit year (e.g. 94)
MMM           Persian month name (e.g. فروردین)
MMI           Dari month name (e.g. حمل)
MM            2-digit month (e.g. 01)
M             month (e.g. 1)
rw            remaining weeks of year
w             week of year
W             week of month
RD            remaining days of year
D             day of year
rd            remaining days of month
dd            2-digit day of month (e.g. 01)
d             day of month (e.g. 1)
E             Persian weekday name (e.g. شنبه)
e             short Persian weekday name (e.g. ش)
A             Persian 12-hour marker (e.g. قبل از ظهر)
a             short Persian 12-hour marker (e.g. ق.ظ)
HH            2-digit hour [00-23]
H             hour [0-23]
kk            2-digit hour [01-24]
k             hour [1-24]
hh            2-digit hour [01-12]
h             hour [1-12]
KK            2-digit hour [00-11]
K             hour [0-11]
mm            2-digit minute [00-59]
m             minute [0-59]
ss            2-digit second [00-59]
s             second [0-59]
n             part of the day (e.g. صبح)
ns            nanosecond, as a plain decimal number
S             3-digit millisecond (e.g. 001)
.000          fractional second, 3 digits
.000000       fractional second, 6 digits
.000000000    fractional second, 9 digits
.999          fractional second, 3 digits, trailing zeros removed
.999999       fractional second, 6 digits, trailing zeros removed
.999999999    fractional second, 9 digits, trailing zeros removed
z             time zone name (e.g. Asia/Tehran)
Z             time zone offset (e.g. +03:30)

A ".999" style fraction is omitted entirely, dot included, when the fractional second is zero.

Example
package main

import (
	"fmt"

	ptime "github.com/amiranmanesh/go-persian-calendar"
)

func main() {
	pt := ptime.Date(1394, ptime.Bahman, 11, 21, 54, 30, 0, ptime.Iran())

	fmt.Println(pt.Format("yyyy/MM/dd E hh:mm:ss a"))
}
Output:
1394/11/11 یک‌شنبه 09:54:30 ب.ظ

func (Time) Hour

func (t Time) Hour() int

Hour returns the hour of t in the range [0, 23].

func (Time) Hour12

func (t Time) Hour12() int

Hour12 returns the hour of t on a 12-hour clock, in the range [0, 11].

func (Time) In

func (t Time) In(loc *time.Location) Time

In returns a copy of t associated with loc.

It changes only the location, not the calendar fields. loc must not be nil.

func (Time) IsLeap

func (t Time) IsLeap() bool

IsLeap reports whether t falls in a leap year.

func (Time) IsZero

func (t Time) IsZero() bool

IsZero reports whether t is the zero Time.

func (Time) LastMonthDay

func (t Time) LastMonthDay() Time

LastMonthDay returns the last day of the month of t, keeping the clock of t.

func (Time) LastWeekday

func (t Time) LastWeekday() Time

LastWeekday returns the last day of the week of t, keeping the clock of t.

func (Time) LastYearDay

func (t Time) LastYearDay() Time

LastYearDay returns the last day of the year of t, keeping the clock of t.

func (Time) Location

func (t Time) Location() *time.Location

Location returns the time zone of t.

func (Time) MarshalJSON

func (t Time) MarshalJSON() ([]byte, error)

MarshalJSON implements [json.Marshaler].

The time is written as a quoted string in RFC3339Nano format. The zero Time is written as null.

Example
package main

import (
	"encoding/json"
	"fmt"

	ptime "github.com/amiranmanesh/go-persian-calendar"
)

func main() {
	type event struct {
		Name string     `json:"name"`
		At   ptime.Time `json:"at"`
	}

	encoded, err := json.Marshal(event{
		Name: "نوروز",
		At:   ptime.Date(1404, ptime.Farvardin, 1, 0, 0, 0, 0, ptime.Iran()),
	})
	if err != nil {
		panic(err)
	}

	fmt.Println(string(encoded))
}
Output:
{"name":"نوروز","at":"1404-01-01T00:00:00+03:30"}

func (Time) MarshalText

func (t Time) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

The time is written in RFC3339Nano format. The zero Time is written as an empty string.

func (Time) Minute

func (t Time) Minute() int

Minute returns the minute of t in the range [0, 59].

func (Time) Month

func (t Time) Month() Month

Month returns the month of t in the range [Farvardin, Esfand].

func (Time) MonthWeek

func (t Time) MonthWeek() int

MonthWeek returns the week of the month of t.

func (Time) Nanosecond

func (t Time) Nanosecond() int

Nanosecond returns the nanosecond of t in the range [0, 999999999].

func (Time) RMonthDay

func (t Time) RMonthDay() int

RMonthDay returns the number of days remaining in the month of t.

func (Time) RYearDay

func (t Time) RYearDay() int

RYearDay returns the number of days remaining in the year of t.

func (Time) RYearWeek

func (t Time) RYearWeek() int

RYearWeek returns the number of weeks remaining in the year of t.

func (Time) Round

func (t Time) Round(d time.Duration) Time

Round returns t rounded to the nearest multiple of d since the zero time, rounding half away from zero. If d <= 0, t is returned unchanged.

func (*Time) Scan

func (t *Time) Scan(src any) error

Scan implements [sql.Scanner].

It accepts NULL, a time.Time, and a Gregorian timestamp in text form. Text is read as Gregorian rather than Persian because that is what Time.Value hands to the driver, and the two are indistinguishable on the wire.

func (Time) Second

func (t Time) Second() int

Second returns the second of t in the range [0, 59].

func (*Time) Set

func (t *Time) Set(year int, month Month, day, hour, minute, sec, nsec int, loc *time.Location)

Set sets every field of t at once.

The arguments may be outside their usual ranges and are normalized. loc must not be nil.

func (*Time) SetDay

func (t *Time) SetDay(day int)

SetDay sets the day of month of t.

func (*Time) SetHour

func (t *Time) SetHour(hour int)

SetHour sets the hour of t.

func (*Time) SetMinute

func (t *Time) SetMinute(minute int)

SetMinute sets the minute of t.

func (*Time) SetMonth

func (t *Time) SetMonth(month Month)

SetMonth sets the month of t.

func (*Time) SetNanosecond

func (t *Time) SetNanosecond(nsec int)

SetNanosecond sets the nanosecond of t.

func (*Time) SetSecond

func (t *Time) SetSecond(sec int)

SetSecond sets the second of t.

func (*Time) SetTime

func (t *Time) SetTime(ti time.Time)

SetTime sets t to the Persian calendar equivalent of the Gregorian time ti.

func (*Time) SetUnix

func (t *Time) SetUnix(sec, nsec int64)

SetUnix sets t to the Unix time sec seconds and nsec nanoseconds since January 1, 1970 UTC.

func (*Time) SetYear

func (t *Time) SetYear(year int)

SetYear sets the year of t.

func (Time) Since deprecated

func (t Time) Since(t2 Time) int64

Since returns the absolute number of seconds between t and t2.

Deprecated: use Time.Sub instead, which returns a signed time.Duration.

func (Time) String

func (t Time) String() string

String returns t in RFC3339Nano format.

The zero Time has no calendar date to render and is reported as "0000-00-00T00:00:00Z".

func (Time) Sub

func (t Time) Sub(u Time) time.Duration

Sub returns the duration t-u.

Example
package main

import (
	"fmt"

	ptime "github.com/amiranmanesh/go-persian-calendar"
)

func main() {
	from := ptime.Date(1394, ptime.Mehr, 2, 8, 0, 0, 0, ptime.Iran())
	to := ptime.Date(1394, ptime.Mehr, 3, 12, 30, 0, 0, ptime.Iran())

	fmt.Println(to.Sub(from))
}
Output:
28h30m0s

func (Time) Time

func (t Time) Time() time.Time

Time converts t back into the Gregorian calendar.

func (Time) TimeFormat

func (t Time) TimeFormat(layout string) string

TimeFormat returns the textual representation of t according to a standard library reference-time layout, as used by time.Time.Format.

2006        4-digit year (e.g. 1394)
06          2-digit year (e.g. 94)
01          2-digit month (e.g. 01)
1           month (e.g. 1)
Jan         month name (e.g. مهر)
January     month name (e.g. مهر)
02          2-digit day of month (e.g. 07)
2           day of month (e.g. 7)
_2          day of month, space padded to 2 characters (e.g. " 7")
Mon         short weekday name (e.g. ش)
Monday      weekday name (e.g. شنبه)
Morning     part of the day (e.g. صبح)
03          2-digit hour [01-12]
3           hour [1-12]
15          2-digit hour [00-23]
04          2-digit minute
4           minute
05          2-digit second
5           second
.000        fractional second, 3 digits
.000000     fractional second, 6 digits
.000000000  fractional second, 9 digits
.999        fractional second, 3 digits, trailing zeros removed
.999999     fractional second, 6 digits, trailing zeros removed
.999999999  fractional second, 9 digits, trailing zeros removed
PM          12-hour marker (e.g. قبل از ظهر)
pm          short 12-hour marker (e.g. ق.ظ)
MST         time zone name
-0700       time zone offset (e.g. +0330)
-07         time zone offset (e.g. +03)
-07:00      time zone offset (e.g. +03:30)
Z0700       time zone offset (e.g. +0330)
Z07:00      time zone offset (e.g. +03:30)

Month names are Dari when the location of t is Afghanistan and Iranian Persian otherwise.

Example
package main

import (
	"fmt"

	ptime "github.com/amiranmanesh/go-persian-calendar"
)

func main() {
	pt := ptime.Date(1394, ptime.Mehr, 2, 14, 7, 8, 0, ptime.Iran())

	fmt.Println(pt.TimeFormat("2 Jan 2006"))
}
Output:
2 مهر 1394

func (Time) Tomorrow

func (t Time) Tomorrow() Time

Tomorrow returns the day after t.

func (Time) Truncate

func (t Time) Truncate(d time.Duration) Time

Truncate returns t rounded down to a multiple of d since the zero time. If d <= 0, t is returned unchanged.

func (Time) Unix

func (t Time) Unix() int64

Unix returns the number of seconds since January 1, 1970 UTC.

func (Time) UnixMicro

func (t Time) UnixMicro() int64

UnixMicro returns the number of microseconds since January 1, 1970 UTC.

func (Time) UnixMilli

func (t Time) UnixMilli() int64

UnixMilli returns the number of milliseconds since January 1, 1970 UTC.

func (Time) UnixNano

func (t Time) UnixNano() int64

UnixNano returns the number of nanoseconds since January 1, 1970 UTC.

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(data []byte) error

UnmarshalJSON implements [json.Unmarshaler].

It expects a quoted string in RFC3339Nano format. A null sets t to the zero Time.

func (*Time) UnmarshalText

func (t *Time) UnmarshalText(data []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

It expects RFC3339Nano format. An empty input sets t to the zero Time.

func (Time) Value

func (t Time) Value() (driver.Value, error)

Value implements driver.Valuer.

The value is handed to the driver as a Gregorian time.Time, so that it is stored as an ordinary SQL timestamp. The zero Time becomes NULL.

func (Time) Weekday

func (t Time) Weekday() Weekday

Weekday returns the day of the week of t.

func (Time) Year

func (t Time) Year() int

Year returns the year of t.

func (Time) YearDay

func (t Time) YearDay() int

YearDay returns the day of the year of t, in the range [1, 366].

func (Time) YearWeek

func (t Time) YearWeek() int

YearWeek returns the week of the year of t.

func (Time) Yesterday

func (t Time) Yesterday() Time

Yesterday returns the day before t.

func (Time) Zone

func (t Time) Zone() (string, int)

Zone returns the time zone abbreviation and its offset in seconds east of UTC.

func (Time) ZoneOffset

func (t Time) ZoneOffset(layout ...string) string

ZoneOffset returns the time zone offset of t as [+|-]HH:mm.

An optional layout selects a different shape; it must be one of "-0700", "-07", "-07:00", "Z0700" or "Z07:00". The "Z" forms render UTC as "Z".

type Weekday

type Weekday int

A Weekday specifies a day of the week, starting from Shanbeh = 0.

const (
	Shanbeh Weekday = iota
	Yekshanbeh
	Doshanbeh
	Seshanbeh
	Charshanbeh
	Panjshanbeh
	Jomeh
)

Days of the week in the Persian calendar.

func (Weekday) IsValid

func (d Weekday) IsValid() bool

IsValid reports whether d is in the range [Shanbeh, Jomeh].

func (Weekday) Short

func (d Weekday) Short() string

Short returns the single letter Persian abbreviation of the day of the week. Out of range values are clamped to Shanbeh and Jomeh.

func (Weekday) String

func (d Weekday) String() string

String returns the Persian name of the day of the week. Out of range values are clamped to Shanbeh and Jomeh.

Directories

Path Synopsis
Package holiday answers whether a Persian date is a public holiday, and what is commemorated on it.
Package holiday answers whether a Persian date is a public holiday, and what is commemorated on it.
internal/gen command
Command gen reconciles the computed holiday calendar with published Iranian calendars and rewrites holiday/data/iran.json.
Command gen reconciles the computed holiday calendar with published Iranian calendars and rewrites holiday/data/iran.json.
internal
jdn
Package jdn converts calendar dates to and from the Julian Day Number, a continuous count of days that is independent of any calendar.
Package jdn converts calendar dates to and from the Julian Day Number, a continuous count of days that is independent of any calendar.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL