cal

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Dec 17, 2018 License: BSD-3-Clause Imports: 2 Imported by: 0

README

cal: Go (golang) calendar library for dealing with holidays and work days

Added Korea holidays
Handling lunar dates codes came from "github.com/xishvai/lunar"

This library augments the Go time package to provide easy handling of holidays and work days (business days).

Holiday instances can be exact days, floating days such as the 3rd Monday of the month, yearly offsets such as the 100th day of the year, or the result of custom function executions for complex rules.

The Calendar type provides functions for calculating workdays and dealing with holidays that are observed on alternate days when they fall on weekends.

Here is a simple usage example of a cron job that runs once per day:

package main

import (
	"time"

	"github.com/suriing/cal"
)

func main() {
	c := cal.NewCalendar()

	// add holidays for the business
	c.AddHoliday(
		cal.USIndependence,
		cal.USThanksgiving,
		cal.USChristmas,
	)

	// optionally change the default of a Mon - Fri work week
	c.SetWorkday(time.Saturday, true)

	// optionally change the holiday calculation behavior
	// (the default is US-style where weekend holidays are
	// observed on the closest weekday)
	c.Observed = cal.ObservedExact

	t := time.Now()

	// run different batch processing jobs based on the day

	if c.IsWorkday(t) {
		// create daily activity reports
	}

	if cal.IsWeekend(t) {
		// validate employee time submissions
	}

	if c.WorkdaysRemain(t) == 10 {
		// 10 business days before the end of month
		// send account statements to customers
	}

	if c.WorkdaysRemain(t) == 0 {
		// last business day of the month
		// execute auto billing transfers
	}
}

Documentation

Overview

Package cal provides extensions to the time package for handling holidays and work days (business days).

Work days are defined as Monday through Friday on dates that are not holidays or the alternate observation dates for holidays.

As in the time package, all calculations assume a Gregorian calendar.

Index

Constants

View Source
const (
	LunarMinYear = 1900
	LunarMaxYear = 2050
)

Handling lunar dates came from "github.com/xishvai/lunar" and modified by suriing Valid year range : 1900~2050

Variables

View Source
var (
	NewYear      = NewHoliday(time.January, 1)
	GoodFriday   = NewHolidayFunc(calculateGoodFriday)
	EasterMonday = NewHolidayFunc(calculateEasterMonday)
	Christmas    = NewHoliday(time.December, 25)
	Christmas2   = NewHoliday(time.December, 26)
)

Common holidays

View Source
var (
	AUNewYear       = NewHolidayFunc(calculateNewYearOceania)
	AUAustralianDay = NewHoliday(time.January, 26)
	AUGoodFriday    = GoodFriday
	AUChristmasDay  = NewHolidayFunc(calculateOcenaniaChristmasDay)
	AUBoxingDays    = Christmas2
	AUEasterMonday  = EasterMonday
	AUAnzacDay      = NewHolidayFunc(calculateAnzacDay)
	AUQueenBirthDay = NewHolidayFunc(calculateQueenBirthDay)
	AULabourDay     = NewHolidayFunc(calculateAULabourDay)
)

Holidays in Australia

View Source
var (
	BENieuwjaar                = NewYear
	BEPaasmaandag              = EasterMonday
	BEDagVanDeArbeid           = ECBLabourDay
	BEOnzeLieveHeerHemelvaart  = NewHolidayFunc(calculateOnzeLieveHeerHemelvaart)
	BEPinkstermaandag          = NewHolidayFunc(calculatePinkstermaandag)
	BENationaleFeestdag        = NewHoliday(time.July, 21)
	BEOnzeLieveVrouwHemelvaart = NewHoliday(time.August, 15)
	BEAllerheiligen            = NewHoliday(time.November, 1)
	BEWapenstilstand           = NewHoliday(time.November, 11)
	BEKerstmis                 = Christmas
)

Holidays in Belgium

View Source
var (
	DENeujahr                = NewYear
	DEHeiligeDreiKoenige     = NewHoliday(time.January, 6)
	DEKarFreitag             = GoodFriday
	DEOstersonntag           = NewHolidayFunc(calculateOstersonntag)
	DEOstermontag            = EasterMonday
	DETagderArbeit           = NewHoliday(time.May, 1)
	DEChristiHimmelfahrt     = NewHolidayFunc(calculateHimmelfahrt)
	DEPfingstsonntag         = NewHolidayFunc(calculatePfingstSonntag)
	DEPfingstmontag          = NewHolidayFunc(calculatePfingstMontag)
	DEFronleichnam           = NewHolidayFunc(calculateFronleichnam)
	DEMariaHimmelfahrt       = NewHoliday(time.August, 15)
	DETagderDeutschenEinheit = NewHoliday(time.October, 3)
	DEReformationstag        = NewHoliday(time.October, 31)
	DEReformationstag2017    = NewHolidayExact(time.October, 31, 2017)
	DEAllerheiligen          = NewHoliday(time.November, 1)
	DEBußUndBettag           = NewHolidayFunc(calculateBußUndBettag)
	DEErsterWeihnachtstag    = Christmas
	DEZweiterWeihnachtstag   = Christmas2
)

Holidays in Germany

View Source
var (
	DKNytaarsdag           = NewYear
	DKSkaertorsdag         = NewHolidayFunc(calculateSkaertorsdag)
	DKLangfredag           = GoodFriday
	DKPaaskedag            = NewHolidayFunc(calculatePaaskedag)
	DKAndenPaaskedag       = EasterMonday
	DKStoreBededag         = NewHolidayFunc(calculateStoreBededag)
	DKKristiHimmelfartsdag = NewHolidayFunc(calculateKristiHimmelfartsdag)
	DKPinsedag             = NewHolidayFunc(calculatePinsedag)
	DKAndenPinsedag        = NewHolidayFunc(calculateAndenPinsedag)
	DKGrundlovsdag         = NewHoliday(time.June, 5)
	DKJuleaften            = NewHoliday(time.December, 24)
	DKJuledag              = Christmas
	DKAndenJuledag         = Christmas2
	DKNytaarsaften         = NewHoliday(time.December, 31)
)

Holidays (official and traditional) in Denmark Reference https://da.wikipedia.org/wiki/Helligdag#Danske_helligdage

View Source
var (
	ECBGoodFriday       = GoodFriday
	ECBEasterMonday     = EasterMonday
	ECBNewYearsDay      = NewYear
	ECBLabourDay        = NewHoliday(time.May, 1)
	ECBChristmasDay     = Christmas
	ECBChristmasHoliday = Christmas2
)

European Central Bank Target2 holidays

View Source
var (
	FRNouvelAn          = NewYear
	FRLundiDePâques     = EasterMonday
	FRFêteDuTravail     = ECBLabourDay
	FRArmistice1945     = NewHoliday(time.May, 8)
	FRJeudiDeLAscension = NewHolidayFunc(calculateJeudiDeLAscension)
	FRLundiDePentecôte  = NewHolidayFunc(calculateLundiDePentecôte)
	FRFêteNationale     = NewHoliday(time.July, 14)
	FRAssomption        = NewHoliday(time.August, 15)
	FRToussaint         = NewHoliday(time.November, 1)
	FRArmistice1918     = NewHoliday(time.November, 11)
	FRNoël              = Christmas
)

Holidays in France

View Source
var (
	GBNewYear       = NewHolidayFunc(calculateNewYearsHoliday)
	GBGoodFriday    = GoodFriday
	GBEasterMonday  = EasterMonday
	GBEarlyMay      = NewHolidayFloat(time.May, time.Monday, 1)
	GBSpringHoliday = NewHolidayFloat(time.May, time.Monday, -1)
	GBSummerHoliday = NewHolidayFloat(time.August, time.Monday, -1)
	GBChristmasDay  = Christmas
	GBBoxingDay     = Christmas2
)

British holidays

View Source
var (
	// International holidays
	KRSolarNewYear = NewYear
	KRChristmasDay = Christmas
	// Korea fixed holidays
	KRMarchFirstDay         = NewHoliday(time.March, 1)   // 삼일절
	KRChildrensDay          = NewHoliday(time.May, 5)     // 어린이날 *대체공휴일
	KRMemorialDay           = NewHoliday(time.June, 6)    // 현충일
	KRIndependenceDay       = NewHoliday(time.August, 15) // 광복절
	KRNationalFoundationDay = NewHoliday(time.October, 3) // 개천절
	KRHangulDay             = NewHoliday(time.October, 9) // 한글날
	// Korea lunar based holidays
	KRLunarNewYears      = NewHolidayFunc(calculateLunarNewYearsHoliday)      // 설날 (음 1/1)	*대체공휴일
	KRLunarNewYears1     = NewHolidayFunc(calculateLunarNewYearsHoliday1)     // 설 연휴 첫날
	KRLunarNewYears2     = NewHolidayFunc(calculateLunarNewYearsHoliday2)     // 설 연휴 마지막날
	KRBuddhasBirthday    = NewHolidayFunc(calculateBuddhasBirthdayHoliday)    // 부처님 오신 날 (음 4/8)
	KRMidautumnFestival  = NewHolidayFunc(calculateMidautumnFestivalHoliday)  // 추석 (음 8/15)	*대체공휴일
	KRMidautumnFestival1 = NewHolidayFunc(calculateMidautumnFestivalHoliday1) // 추석 연휴 첫날
	KRMidautumnFestival2 = NewHolidayFunc(calculateMidautumnFestivalHoliday2) // 추석 연휴 마지막날
)

Korea holidays

View Source
var (
	NLNieuwjaar       = NewYear
	NLGoedeVrijdag    = GoodFriday
	NLPaasMaandag     = EasterMonday
	NLKoningsDag      = NewHolidayFunc(calculateKoningsDag)
	NLBevrijdingsDag  = NewHoliday(time.May, 5)
	NLHemelvaart      = DEChristiHimmelfahrt
	NLPinksterMaandag = DEPfingstmontag
	NLEersteKerstdag  = Christmas
	NLTweedeKerstdag  = Christmas2
)

Holidays in the Netherlands

View Source
var (
	NOFoersteNyttaarsdag   = NewYear
	NOSkjaertorsdag        = NewHolidayFunc(calculateSkaertorsdag)
	NOLangfredag           = GoodFriday
	NOFoerstePaaskedag     = NewHolidayFunc(calculatePaskdagen)
	NOAndrePaaskedag       = EasterMonday
	NOArbeiderenesdag      = NewHoliday(time.May, 1)
	NOGrunnlovsdag         = NewHoliday(time.May, 17)
	NOKristihimmelfartsdag = NewHolidayFunc(calculateKristiHimmelfardsdag)
	NOFoerstePinsedag      = NewHolidayFunc(calculatePingstdagen)
	NOAndrePinsedag        = NewHolidayFunc(calculateAndenPinsedag)
	NOFoersteJuledag       = Christmas
	NOAndreJuledag         = Christmas2
	// Half days
	NOJulaften      = NewHoliday(time.December, 24)
	NONyttaarsaften = NewHoliday(time.December, 31)
)

Holidays in Norway Reference https://no.wikipedia.org/wiki/Helligdager_i_Norge

View Source
var (
	NZNewYear         = NewHolidayFunc(calculateNewYearOceania)
	NZGoodFriday      = GoodFriday
	NZChristmasDay    = NewHolidayFunc(calculateOcenaniaChristmasDay)
	NZBoxingDays      = NewHolidayFunc(calculateOcenaniaBoxingDay)
	NZEasterMonday    = EasterMonday
	NZAnzacDay        = NewHolidayFunc(calculateNZAnzacDay)
	NZQueensBirthday  = NewHolidayFunc(calculateQueensBirthday)
	NZLabourDay       = NewHolidayFunc(calculateLabourDay)
	NZDayAfterNewYear = NewHolidayFunc(calculateDayAfterNewYear)
	NZWanagiDay       = NewHolidayFunc(calculateWarangiDay)
)

Holidays in Australia

View Source
var (
	SENyarsdagen           = NewYear
	SETrettondedagJul      = NewHoliday(time.January, 6)
	SELangfredagen         = GoodFriday
	SEPaskdagen            = NewHolidayFunc(calculatePaskdagen)
	SEAnnandagPask         = EasterMonday
	SEForstaMaj            = NewHoliday(time.May, 1)
	SEKristiHimmelfardsdag = NewHolidayFunc(calculateKristiHimmelfardsdag)
	SEPingstdagen          = NewHolidayFunc(calculatePingstdagen)
	SENationaldagen        = NewHoliday(time.June, 6)
	SEMidsommarafton       = NewHolidayFunc(calculateMidsommarafton)
	SEMidsommardagen       = NewHolidayFunc(calculateMidsommardagen)
	SEAllaHelgonsDag       = NewHolidayFunc(calculateAllaHelgonsDag)
	SEJulafton             = NewHoliday(time.December, 24)
	SEJuldagen             = Christmas
	SEAnnandagJul          = Christmas2
	SENewYearsEve          = NewHoliday(time.December, 31)
)

Holidays in Sweden Reference https://sv.wikipedia.org/wiki/Helgdagar_i_Sverige Days with the [2] notation, meaning days with reduced working hours haven't been added, as this is not regulated by law.

View Source
var (
	USNewYear      = NewYear
	USMLK          = NewHolidayFloat(time.January, time.Monday, 3)
	USPresidents   = NewHolidayFloat(time.February, time.Monday, 3)
	USMemorial     = NewHolidayFloat(time.May, time.Monday, -1)
	USIndependence = NewHoliday(time.July, 4)
	USLabor        = NewHolidayFloat(time.September, time.Monday, 1)
	USColumbus     = NewHolidayFloat(time.October, time.Monday, 2)
	USVeterans     = NewHoliday(time.November, 11)
	USThanksgiving = NewHolidayFloat(time.November, time.Thursday, 4)
	USChristmas    = Christmas
)

US holidays

View Source
var (
	LunarBase = time.Date(LunarMinYear, 1, 31, 0, 0, 0, 0, time.Local)
)

Functions

func AddAustralianHolidays

func AddAustralianHolidays(c *Calendar)

AddAustralianHolidays adds all Australian holidays

func AddBelgiumHolidays

func AddBelgiumHolidays(c *Calendar)

AddBelgiumHolidays adds all Belgium holidays to the Calendar

func AddBritishHolidays

func AddBritishHolidays(c *Calendar)

AddBritishHolidays adds all British holidays to the Calender

func AddDanishHolidays

func AddDanishHolidays(c *Calendar)

AddDanishHolidays adds all Danish holidays to the Calendar

func AddDanishTraditions

func AddDanishTraditions(c *Calendar)

AddDanishTraditions adds Grundlovsdag (Constitution Day), Christmas Eve, and New Years Eve which are not official holidays.

func AddDutchHolidays

func AddDutchHolidays(c *Calendar)

AddDutchHolidays adds all Dutch holidays to the Calendar

func AddEcbHolidays

func AddEcbHolidays(c *Calendar)

AddEcbHolidays adds all ECB Target2 holidays to the calendar

func AddFranceHolidays

func AddFranceHolidays(c *Calendar)

AddFranceHolidays adds all France holidays to the Calendar

func AddGermanHolidays

func AddGermanHolidays(c *Calendar)

AddGermanHolidays adds all German holidays to the Calendar

func AddGermanyStateHolidays

func AddGermanyStateHolidays(c *Calendar, state string)

AddGermanyStateHolidays adds german state holidays to the calendar

func AddKoreaHolidays

func AddKoreaHolidays(c *Calendar)

AddKoreaHolidays adds all Korea holidays to the Calender

func AddNewZealandHoliday

func AddNewZealandHoliday(c *Calendar)

AddNewZelandHoliday adds all New Zeland holidays

func AddNorwegianHalfDays

func AddNorwegianHalfDays(c *Calendar)

AddNorwegianHalfDays are note holidays, but often practiced as a half-business day.

func AddNorwegianHolidays

func AddNorwegianHolidays(c *Calendar)

AddNorwegianHolidays adds all Norwegian holidays to Calendar

func AddSwedishHolidays

func AddSwedishHolidays(c *Calendar)

AddSwedishHolidays adds all Swedish holidays to the Calendar

func AddUsHolidays

func AddUsHolidays(cal *Calendar)

AddUsHolidays adds all US holidays to the Calendar

func IsLeap

func IsLeap(year int) bool

func IsWeekdayN

func IsWeekdayN(date time.Time, day time.Weekday, n int) bool

IsWeekdayN reports whether the given date is the nth occurrence of the day in the month.

The value of n affects the direction of counting:

n > 0: counting begins at the first day of the month.
n == 0: the result is always false.
n < 0: counting begins at the end of the month.

func IsWeekend

func IsWeekend(date time.Time) bool

IsWeekend reports whether the given date falls on a weekend.

func JulianDate

func JulianDate(t time.Time) float32

JulianDate reports the Julian Date (which includes time as a fraction) for t.

func JulianDayNumber

func JulianDayNumber(t time.Time) int

JulianDayNumber reports the Julian Day Number for t. Note that Julian days start at 12:00 UTC.

func LeapDays

func LeapDays(year int) int

the days of this year's leap month

func LeapMonth

func LeapMonth(year int) int

which month leaps in this year? return 1-12(if there is one) or 0(no leap month).

func MonthDays

func MonthDays(year, month int) int

the days of the m-th month of this year

func MonthEnd

func MonthEnd(t time.Time) time.Time

MonthEnd reports the ending day of the month in t. The time portion is unchanged.

func MonthStart

func MonthStart(t time.Time) time.Time

MonthStart reports the starting day of the month in t. The time portion is unchanged.

func YearDays

func YearDays(year int) int

the total days of this year

Types

type Calendar

type Calendar struct {
	Observed ObservedRule
	// contains filtered or unexported fields
}

Calendar represents a yearly calendar with a list of holidays.

func NewCalendar

func NewCalendar() *Calendar

NewCalendar creates a new Calendar with no holidays defined and work days of Monday through Friday.

func (*Calendar) AddHoliday

func (c *Calendar) AddHoliday(h ...Holiday)

AddHoliday adds a holiday to the calendar's list.

func (*Calendar) AddSkipNonWorkdays

func (c *Calendar) AddSkipNonWorkdays(start time.Time, d time.Duration) time.Time

AddSkipNonWorkdays returns start time plus d woking duration

func (*Calendar) CountHolidayHoursWithOffset

func (c *Calendar) CountHolidayHoursWithOffset(start time.Time, offsetHour int) int

CountHolidayHoursWithOffset returns the number of working hours in a range starting from the consumed start date to the end date set by the offset

func (*Calendar) CountWorkdays

func (c *Calendar) CountWorkdays(start, end time.Time) int64

CountWorkdays return amount of workdays between start and end dates

func (*Calendar) IsHoliday

func (c *Calendar) IsHoliday(date time.Time) bool

IsHoliday reports whether a given date is a holiday. It does not account for the observation of holidays on alternate days.

func (*Calendar) IsWorkday

func (c *Calendar) IsWorkday(date time.Time) bool

IsWorkday reports whether a given date is a work day (business day).

func (*Calendar) SetWorkday

func (c *Calendar) SetWorkday(day time.Weekday, workday bool)

SetWorkday changes the given day's status as a standard working day

func (*Calendar) WorkdayN

func (c *Calendar) WorkdayN(year int, month time.Month, n int) int

WorkdayN reports the day of the month that corresponds to the nth workday for the given year and month.

The value of n affects the direction of counting:

n > 0: counting begins at the first day of the month.
n == 0: the result is always 0.
n < 0: counting begins at the end of the month.

func (*Calendar) Workdays

func (c *Calendar) Workdays(year int, month time.Month) int

Workdays reports the total number of workdays for the given year and month.

func (*Calendar) WorkdaysFrom

func (c *Calendar) WorkdaysFrom(start time.Time, offset int) time.Time

WorkdaysFrom reports the date of a workday that is offset days away from start.

If n > 0, then the date returned is start + offset workdays. If n == 0, then the date is returned unchanged. If n < 0, then the date returned is start - offset workdays.

func (*Calendar) WorkdaysRemain

func (c *Calendar) WorkdaysRemain(date time.Time) int

WorkdaysRemain reports the total number of remaining workdays in the month for the given date.

type Holiday

type Holiday struct {
	Month   time.Month
	Weekday time.Weekday
	Day     int
	Offset  int
	Year    int
	Func    HolidayFn
	// contains filtered or unexported fields
}

Holiday holds information about the yearly occurrence of a holiday.

A valid Holiday consists of one of the following: - Month and Day (such as March 14 for Pi Day) - Month, Weekday, and Offset (such as the second Monday of October for Columbus Day) - Offset (such as the 183rd day of the year for the start of the second half) - Month, Day, and Year (in case you want to specify holidays exactly for each year) - Func (to calculate the holiday)

func NewHoliday

func NewHoliday(month time.Month, day int) Holiday

NewHoliday creates a new Holiday instance for an exact day of a month.

func NewHolidayExact

func NewHolidayExact(month time.Month, day int, year int) Holiday

NewHolidayExact creates a new Holiday instance for an exact day of a month and year.

func NewHolidayFloat

func NewHolidayFloat(month time.Month, weekday time.Weekday, offset int) Holiday

NewHolidayFloat creates a new Holiday instance for an offset-based day of a month.

func NewHolidayFunc

func NewHolidayFunc(fn HolidayFn) Holiday

NewHolidayFunc creates a new Holiday instance that uses a function to calculate the day and month.

type HolidayFn

type HolidayFn func(year int, loc *time.Location) (month time.Month, day int)

HolidayFn calculates the occurrence of a holiday for the given year. This is useful for holidays like Easter that depend on complex rules.

type Lunar

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

func NewLunar

func NewLunar(year, month, day, hour, min, sec int, loc *time.Location) *Lunar

func (*Lunar) Convert

func (l *Lunar) Convert() time.Time

func (*Lunar) Day

func (l *Lunar) Day() int

func (*Lunar) Hour

func (l *Lunar) Hour() int

func (*Lunar) Location

func (l *Lunar) Location() *time.Location

func (*Lunar) Minute

func (l *Lunar) Minute() int

func (*Lunar) Month

func (l *Lunar) Month() int

func (*Lunar) Second

func (l *Lunar) Second() int

func (*Lunar) Year

func (l *Lunar) Year() int

type ObservedRule

type ObservedRule int

ObservedRule represents a rule for observing a holiday that falls on a weekend.

const (
	ObservedNearest ObservedRule = iota // nearest weekday (Friday or Monday)
	ObservedExact                       // the exact day only
	ObservedMonday                      // Monday always
)

ObservedRule are the specific ObservedRules

Jump to

Keyboard shortcuts

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