timefy

package module
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Jul 25, 2026 License: GPL-3.0 Imports: 4 Imported by: 0

README

timefy

timefy is a comprehensive Go library designed to enhance productivity by offering a wide range of time-related utilities. Whether you're dealing with date formatting, time zone conversions, or scheduling. Timefy provides a robust toolkit to simplify time management tasks in Go applications.

Requirements
  • Go version 1.23 or higher
Installation

To install, you can use the following commands based on your preference:

  • For a specific version:

    go get github.com/polarixa/timefy@v0.0.3
    
  • For the latest version:

    go get github.com/polarixa/timefy@latest
    
Getting started
Getting timefy

With Go's module support, go [build|run|test] automatically fetches the necessary dependencies when you add the import in your code:

import "github.com/polarixa/timefy"
Usage

Calculating the time based on current time

package main

import (
	"fmt"
	"time"

	"github.com/polarixa/timefy"
)

func main() {
	// time based on current time
	tx := timefy.With(time.Now())        // 2024-10-25 21:31:00.690342
	fmt.Println(tx.BeginningOfMinute())  // 2024-10-25 21:31:00
	fmt.Println(tx.BeginningOfHour())    // 2024-10-25 21:00:00
	fmt.Println(tx.BeginningOfDay())     // 2024-10-25 00:00:00
	fmt.Println(tx.BeginningOfWeek())    // 2024-10-20 00:00:00
	fmt.Println(tx.BeginningOfMonth())   // 2024-10-01 00:00:00
	fmt.Println(tx.BeginningOfQuarter()) // 2024-10-01 00:00:00
	fmt.Println(tx.BeginningOfHalf())    // 2024-07-01 00:00:00
	fmt.Println(tx.BeginningOfYear())    // 2024-01-01 00:00:00
	fmt.Println(tx.EndOfMinute())        // 2024-10-25 21:31:59.999999999 +0700 +07
	fmt.Println(tx.EndOfHour())          // 2024-10-25 21:59:59.999999999 +0700 +07
	fmt.Println(tx.EndOfDay())           // 2024-10-25 23:59:59.999999999 +0700 +07
	fmt.Println(tx.EndOfWeek())          // 2024-10-26 23:59:59.999999999 +0700 +07
	fmt.Println(tx.EndOfMonth())         // 2024-10-31 23:59:59.999999999 +0700 +07
	fmt.Println(tx.EndOfQuarter())       // 2024-12-31 23:59:59.999999999 +0700 +07
	fmt.Println(tx.EndOfHalf())          // 2024-12-31 23:59:59.999999999 +0700 +07
	fmt.Println(tx.EndOfYear())          // 2024-12-31 23:59:59.999999999 +0700 +07

	fmt.Println(tx.EndOfWeek())          // 2024-10-28 23:59:59.999999999 +0700 +07
}

Calculating the time based on another time

package main

import (
	"fmt"
	"time"

	"github.com/polarixa/timefy"
)

func main() {
	// time based on another time
	t := time.Date(2025, 01, 15, 17, 51, 49, 123456789, time.Local)
	tx := timefy.New(t)           // or timefy.With(t)
	fmt.Println(tx.EndOfMonth()) // 2025-01-31 23:59:59.999999999 +0700 +07
}

Calculating the time based on configuration

package main

import (
	"fmt"
	"time"

	"github.com/polarixa/timefy"
)

func main() {
	// time based on configuration
	rule := timefy.NewRule().WithLocationRFC(timefy.DefaultTimezoneVietnam)
	t := time.Date(2025, 01, 15, 17, 51, 49, 123456789, time.Now().Location())
	fmt.Println(t)                              // 2025-01-15 17:51:49.123456789 +0700 +07
	fmt.Println(rule.With(t).BeginningOfWeek()) // 2025-01-12 00:00:00 +0700 +07
	v, _ := rule.Parse("2025-11-12 22:14:01")
	fmt.Println(v) // 2025-11-12 22:14:01 +0700 +07
}

Monday / Sunday

package main

import (
	"fmt"
	"time"

	"github.com/polarixa/timefy"
)

func main() {
	// Monday / Sunday
	t := time.Date(2025, 01, 15, 17, 51, 49, 123456789, time.Now().Location())
	fmt.Println(timefy.Monday())                   // 2024-10-21 00:00:00 +0700 +07
	fmt.Println(timefy.Monday("15:35:34"))         // 2024-10-21 15:35:34 +0700 +07
	fmt.Println(timefy.Sunday())                   // 2024-10-27 00:00:00 +0700 +07
	fmt.Println(timefy.Sunday("16:45:34"))         // 2024-10-27 16:45:34 +0700 +07
	fmt.Println(timefy.EndOfSunday())              // 2024-10-27 23:59:59.999999999 +0700 +07
	fmt.Println(timefy.With(t).Monday())           // 2025-01-13 00:00:00 +0700 +07
	fmt.Println(timefy.With(t).Monday("15:35:34")) // 2025-01-13 15:35:34 +0700 +07
	fmt.Println(timefy.With(t).Sunday())           // 2025-01-19 00:00:00 +0700 +07
	fmt.Println(timefy.With(t).Sunday("16:45:34")) // 2025-01-19 16:45:34 +0700 +07
	fmt.Println(timefy.With(t).EndOfSunday())      // 2025-01-19 23:59:59.999999999 +0700 +07
}

Parse String to Time

package main

import (
	"fmt"

	"github.com/polarixa/timefy"
)

func main() {
	// String to Time
	t, _ := timefy.Parse("2025")
	fmt.Println(t) // 2025-01-01 00:00:00 +0700 +07
	t, _ = timefy.Parse("2025-02")
	fmt.Println(t) // 2025-02-01 00:00:00 +0700 +07
	t, _ = timefy.Parse("2025-02-15")
	fmt.Println(t) // 2025-02-15 00:00:00 +0700 +07
	t, _ = timefy.Parse("11-15")
	fmt.Println(t) // 2024-11-15 00:00:00 +0700 +07
	t, _ = timefy.Parse("13:15")
	fmt.Println(t) // 2024-10-25 13:15:00 +0700 +07
	t, _ = timefy.Parse("13:15:45")
	fmt.Println(t) // 2024-10-25 13:15:45 +0700 +07
	t, _ = timefy.Parse("23")
	fmt.Println(t) // 2024-10-25 23:00:00 +0700 +07
	// MustParse must parse string to time or it will panic
	t = timefy.MustParse("11")
	fmt.Println(t) // 2024-10-25 11:00:00 +0700 +07
	t = timefy.MustParse("99:99") // panic: can't parse string as time: 99:99
	// fmt.Println(t)

	// Extend timefy to support more formats is quite easy, just update timefy.TimeFormats with other time layouts, e.g:
	timefy.TimeFormats = append(timefy.TimeFormats, "02 Jan 2006 15:04")
	fmt.Println(timefy.TimeFormats)
}

Parse in Location

package main

import (
	"fmt"
	"time"

	"github.com/polarixa/timefy"
)

func main() {
	// ParseInLocation parses in a specific timezone
	t, err := timefy.ParseInLocation(time.UTC, "2023-10-25")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println(t) // 2023-10-25 00:00:00 +0000 UTC

	// MustParseInLocation panics on error
	t = timefy.MustParseInLocation(time.UTC, "2023-10-25 14:30:00")
	fmt.Println(t) // 2023-10-25 14:30:00 +0000 UTC
}

Day Operations

package main

import (
	"fmt"
	"time"

	"github.com/polarixa/timefy"
)

func main() {
	now := time.Date(2025, 01, 15, 17, 51, 49, 0, time.UTC)

	// BeginOfDay returns the start of the day (00:00:00)
	fmt.Println(timefy.BeginOfDay(now)) // 2025-01-15 00:00:00 +0000 UTC

	// FEndOfDay returns the end of the day (23:59:59)
	fmt.Println(timefy.FEndOfDay(now)) // 2025-01-15 23:59:59 +0000 UTC

	// PrevBeginOfDay returns the start of the day N days ago
	fmt.Println(timefy.PrevBeginOfDay(now, 2)) // 2025-01-13 00:00:00 +0000 UTC

	// PrevEndOfDay returns the end of the day N days ago
	fmt.Println(timefy.PrevEndOfDay(now, 2)) // 2025-01-13 23:59:59 +0000 UTC
}

Time Manipulation (Add/Subtract)

package main

import (
	"fmt"
	"time"

	"github.com/polarixa/timefy"
)

func main() {
	now := time.Date(2025, 01, 15, 12, 0, 0, 0, time.UTC)

	// AddSecond adds seconds (negative to subtract)
	fmt.Println(timefy.AddSecond(now, 30))  // 2025-01-15 12:00:30 +0000 UTC
	fmt.Println(timefy.AddSecond(now, -30)) // 2025-01-15 11:59:30 +0000 UTC

	// AddMinute adds minutes
	fmt.Println(timefy.AddMinute(now, 10))  // 2025-01-15 12:10:00 +0000 UTC
	fmt.Println(timefy.AddMinute(now, -10)) // 2025-01-15 11:50:00 +0000 UTC

	// AddHour adds hours
	fmt.Println(timefy.AddHour(now, 3))  // 2025-01-15 15:00:00 +0000 UTC
	fmt.Println(timefy.AddHour(now, -3)) // 2025-01-15 09:00:00 +0000 UTC

	// AddDay adds days
	fmt.Println(timefy.AddDay(now, 5))  // 2025-01-20 12:00:00 +0000 UTC
	fmt.Println(timefy.AddDay(now, -5)) // 2025-01-10 12:00:00 +0000 UTC
}

Timezone Utilities

package main

import (
	"fmt"
	"time"

	"github.com/polarixa/timefy"
)

func main() {
	now := time.Date(2025, 01, 15, 12, 0, 0, 0, time.UTC)

	// SetTimezone converts time to a specific timezone (returns error if invalid)
	nyTime, err := timefy.SetTimezone(now, "America/New_York")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println(nyTime) // 2025-01-15 07:00:00 -0500 EST

	// AdjustTimezone converts time (returns original time on invalid timezone)
	tokyoTime := timefy.AdjustTimezone(now, "Asia/Tokyo")
	fmt.Println(tokyoTime) // 2025-01-15 21:00:00 +0900 JST

	invalidTZ := timefy.AdjustTimezone(now, "Invalid/Zone")
	fmt.Println(invalidTZ) // 2025-01-15 12:00:00 +0000 UTC (original time returned)
}

Leap Year & Tolerance Checks

package main

import (
	"fmt"
	"time"

	"github.com/polarixa/timefy"
)

func main() {
	// IsLeapYear checks if a year is a leap year
	fmt.Println(timefy.IsLeapYear(2024)) // true
	fmt.Println(timefy.IsLeapYear(2023)) // false
	fmt.Println(timefy.IsLeapYear(1900)) // false
	fmt.Println(timefy.IsLeapYear(2000)) // true

	// IsLeapYearN checks using a time.Time value
	t := time.Date(2024, 6, 15, 0, 0, 0, 0, time.UTC)
	fmt.Println(timefy.IsLeapYearN(t)) // true

	// IsWithinTolerance checks if a time is within 1 minute of now
	now := time.Now()
	fmt.Println(timefy.IsWithinTolerance(now.Add(30 * time.Second)))  // true
	fmt.Println(timefy.IsWithinTolerance(now.Add(2 * time.Minute)))   // false
}

Between (String-based Range Check)

package main

import (
	"fmt"

	"github.com/polarixa/timefy"
)

func main() {
	// Between checks if the current time is between two time strings
	isWithin := timefy.Between("2020-01-01", "2030-12-31")
	fmt.Println(isWithin) // true (current time is between these dates)

	isWithin = timefy.Between("2030-01-01", "2030-12-31")
	fmt.Println(isWithin) // false (current time is not in 2030 yet)
}

Quarter

package main

import (
	"fmt"
	"time"

	"github.com/polarixa/timefy"
)

func main() {
	// Quarter returns the current quarter (1-4)
	fmt.Println(timefy.Quarter()) // e.g., 1 for January-March

	// Quarter on a Timex instance
	t := time.Date(2025, 7, 15, 0, 0, 0, 0, time.UTC)
	fmt.Println(timefy.New(t).Quarter()) // 3 (July is Q3)
}

Since (Elapsed Time Calculations)

package main

import (
	"fmt"
	"time"

	"github.com/polarixa/timefy"
)

func main() {
	past := time.Now().Add(-2 * time.Hour)

	// SinceHour returns the number of hours passed
	fmt.Println(timefy.SinceHour(past)) // ~2.0

	// SinceMinute returns the number of minutes passed
	fmt.Println(timefy.SinceMinute(past)) // ~120.0

	// SinceSecond returns the number of seconds passed
	fmt.Println(timefy.SinceSecond(past)) // ~7200.0
}

Weekdays in Range

package main

import (
	"fmt"
	"time"

	"github.com/polarixa/timefy"
)

func main() {
	start := time.Date(2025, 1, 13, 0, 0, 0, 0, time.UTC) // Monday
	end := time.Date(2025, 1, 19, 0, 0, 0, 0, time.UTC)   // Sunday

	// GetWeekdaysInRange returns all weekdays (Mon-Fri) in the range
	weekdays := timefy.GetWeekdaysInRange(start, end)
	for _, d := range weekdays {
		fmt.Println(d) // 2025-01-13, 2025-01-14, 2025-01-15, 2025-01-16, 2025-01-17
	}
}

FormatTimex (Extract Time Components)

package main

import (
	"fmt"
	"time"

	"github.com/polarixa/timefy"
)

func main() {
	t := time.Date(2025, 3, 15, 14, 30, 45, 123456789, time.UTC)

	// FormatTimex returns a slice of time components: [nanosecond, second, minute, hour, day, month, year]
	components := timefy.FormatTimex(t)
	fmt.Println(components) // [123456789 45 30 14 15 3 2025]
}

Formatting (RFC Layouts)

package main

import (
	"fmt"
	"time"

	"github.com/polarixa/timefy"
)

func main() {
	t := time.Date(2025, 8, 15, 13, 45, 30, 0, time.UTC)

	// FormatRFC formats the current time using a TimeFormatRFC layout
	fmt.Println(timefy.FormatRFC(timefy.TimeFormat20060102T150405))

	// FormatRFCshort formats the current time using a short TimeRFC layout
	fmt.Println(timefy.FormatRFCshort(timefy.TimeRFC01T150405))

	// FFormatRFC formats a specific time with a TimeFormatRFC layout
	fmt.Println(timefy.FFormatRFC(t, timefy.TimeFormat20060102T150405)) // 2025-08-15T13:45:30

	// FFormatRFCshort formats a specific time with a short TimeRFC layout
	fmt.Println(timefy.FFormatRFCshort(t, timefy.TimeRFC01T150405)) // 13:45:30

	// DefaultFormatRFC formats the current time with the default layout
	fmt.Println(timefy.DefaultFormatRFC())

	// FDefaultFormatRFC formats a specific time with the default layout
	fmt.Println(timefy.FDefaultFormatRFC(t))
}

Relative Time (TimeAgo / TimeUntil)

package main

import (
	"fmt"
	"time"

	"github.com/polarixa/timefy"
)

func main() {
	// TimeAgo returns a human-readable string for past time
	fmt.Println(timefy.New(time.Now().Add(-5 * time.Second)).TimeAgo())  // "just now"
	fmt.Println(timefy.New(time.Now().Add(-5 * time.Minute)).TimeAgo()) // "5 minutes ago"
	fmt.Println(timefy.New(time.Now().Add(-2 * time.Hour)).TimeAgo())   // "2 hours ago"
	fmt.Println(timefy.New(time.Now().Add(-48 * time.Hour)).TimeAgo())  // "2 days ago"
	fmt.Println(timefy.New(time.Now().Add(-720 * time.Hour)).TimeAgo()) // "1 month ago"

	// TimeUntil returns a human-readable string for future time
	fmt.Println(timefy.New(time.Now().Add(5 * time.Second)).TimeUntil())  // "in a few seconds"
	fmt.Println(timefy.New(time.Now().Add(5 * time.Minute)).TimeUntil()) // "in 5 minutes"
	fmt.Println(timefy.New(time.Now().Add(2 * time.Hour)).TimeUntil())   // "in 2 hours"
	fmt.Println(timefy.New(time.Now().Add(48 * time.Hour)).TimeUntil())  // "in 2 days"

	// TimeUntil with past time
	fmt.Println(timefy.New(time.Now().Add(-1 * time.Hour)).TimeUntil()) // "in the past"
}

Duration Calculations

package main

import (
	"fmt"
	"time"

	"github.com/polarixa/timefy"
)

func main() {
	now := time.Date(2025, 1, 15, 0, 0, 0, 0, time.UTC)
	tx := timefy.New(now)

	// DurationInDays returns the number of days between two times
	future := now.AddDate(0, 0, 10)
	fmt.Println(tx.DurationInDays(future)) // 10

	// DurationInWeeks returns the number of weeks between two times
	future = now.AddDate(0, 0, 21)
	fmt.Println(tx.DurationInWeeks(future)) // 3

	// DurationInMonths returns the number of months between two times
	future = now.AddDate(0, 3, 0)
	fmt.Println(tx.DurationInMonths(future)) // 3

	// DurationInYears returns the number of years between two times
	future = now.AddDate(2, 0, 0)
	fmt.Println(tx.DurationInYears(future)) // 2
}

Day Type Checks (Weekend / Weekday)

package main

import (
	"fmt"
	"time"

	"github.com/polarixa/timefy"
)

func main() {
	saturday := time.Date(2025, 1, 18, 12, 0, 0, 0, time.UTC)
	monday := time.Date(2025, 1, 20, 12, 0, 0, 0, time.UTC)

	// IsWeekend checks if the time is Saturday or Sunday
	fmt.Println(timefy.New(saturday).IsWeekend()) // true
	fmt.Println(timefy.New(monday).IsWeekend())   // false

	// IsWeekday checks if the time is Monday to Friday
	fmt.Println(timefy.New(saturday).IsWeekday()) // false
	fmt.Println(timefy.New(monday).IsWeekday())   // true
}

Time Comparison Helpers

package main

import (
	"fmt"
	"time"

	"github.com/polarixa/timefy"
)

func main() {
	now := time.Now()
	tx := timefy.New(now)

	yesterday := now.AddDate(0, 0, -1)
	tomorrow := now.AddDate(0, 0, 1)

	// IsBefore checks if the time is before another time
	fmt.Println(tx.IsBefore(tomorrow))  // true
	fmt.Println(tx.IsBefore(yesterday)) // false

	// IsAfter checks if the time is after another time
	fmt.Println(tx.IsAfter(yesterday)) // true
	fmt.Println(tx.IsAfter(tomorrow))  // false

	// IsBetween checks if the time falls within a range (inclusive)
	fmt.Println(tx.IsBetween(yesterday, tomorrow)) // true

	// IsSameDay checks if two times are on the same day
	fmt.Println(tx.IsSameDay(now))       // true
	fmt.Println(tx.IsSameDay(yesterday)) // false

	// IsSameMonth checks if two times are in the same month
	nextMonth := now.AddDate(0, 1, 0)
	fmt.Println(tx.IsSameMonth(now))       // true
	fmt.Println(tx.IsSameMonth(nextMonth)) // false

	// IsSameYear checks if two times are in the same year
	nextYear := now.AddDate(1, 0, 0)
	fmt.Println(tx.IsSameYear(now))      // true
	fmt.Println(tx.IsSameYear(nextYear)) // false
}

Temporal Checks (Today / Yesterday / Tomorrow / Past / Future)

package main

import (
	"fmt"
	"time"

	"github.com/polarixa/timefy"
)

func main() {
	now := time.Now()

	// IsToday checks if the time is today
	fmt.Println(timefy.New(now).IsToday()) // true

	// IsYesterday checks if the time is yesterday
	yesterday := now.AddDate(0, 0, -1)
	fmt.Println(timefy.New(yesterday).IsYesterday()) // true

	// IsTomorrow checks if the time is tomorrow
	tomorrow := now.AddDate(0, 0, 1)
	fmt.Println(timefy.New(tomorrow).IsTomorrow()) // true

	// IsPast checks if the time is in the past
	past := now.Add(-1 * time.Hour)
	fmt.Println(timefy.New(past).IsPast()) // true

	// IsFuture checks if the time is in the future
	future := now.Add(1 * time.Hour)
	fmt.Println(timefy.New(future).IsFuture()) // true
}

Global Convenience Functions (BeginningOf / EndOf)

package main

import (
	"fmt"

	"github.com/polarixa/timefy"
)

func main() {
	// These global functions use the current time automatically
	fmt.Println(timefy.BeginningOfMinute())  // Current time at start of minute
	fmt.Println(timefy.BeginningOfHour())    // Current time at start of hour
	fmt.Println(timefy.BeginningOfDay())     // Today at 00:00:00
	fmt.Println(timefy.BeginningOfWeek())    // Start of current week
	fmt.Println(timefy.BeginningOfMonth())   // 1st of current month at 00:00:00
	fmt.Println(timefy.BeginningOfQuarter()) // 1st of current quarter
	fmt.Println(timefy.BeginningOfYear())    // Jan 1st of current year

	fmt.Println(timefy.EndOfMinute())  // Current time at end of minute
	fmt.Println(timefy.EndOfHour())    // Current time at end of hour
	fmt.Println(timefy.EndOfDay())     // Today at 23:59:59.999999999
	fmt.Println(timefy.EndOfWeek())    // End of current week
	fmt.Println(timefy.EndOfMonth())   // Last day of current month at 23:59:59.999999999
	fmt.Println(timefy.EndOfQuarter()) // Last day of current quarter
	fmt.Println(timefy.EndOfYear())    // Dec 31st at 23:59:59.999999999
}

Configuration (Rule) — Complete API

package main

import (
	"fmt"
	"time"

	"github.com/polarixa/timefy"
)

func main() {
	// NewRule creates a rule with default configuration
	rule := timefy.NewRule()

	// WithWeekStartDay sets the week start day
	rule.WithWeekStartDay(time.Monday)

	// WithTimeFormats overrides the time formats
	rule.WithTimeFormats([]string{"2006-01-02 15:04:05"})

	// WithLocation sets the location using *time.Location
	rule.WithLocation(time.UTC)

	// WithLocationRFC sets location using a predefined zone string
	rule.WithLocationRFC(timefy.DefaultTimezoneVietnam)

	// ApplyUTCLoc sets location to UTC
	rule.ApplyUTCLoc()

	// ApplyLocalLoc sets location to Local
	rule.ApplyLocalLoc()

	// AppendTimeFormat appends custom format strings
	rule.AppendTimeFormat("02 Jan 2006 15:04")

	// AppendTimeFormatRFC appends defined RFC format constants
	rule.AppendTimeFormatRFC(timefy.TimeFormat20060102T150405)

	// AppendTimeFormatRFCshort appends defined short RFC format constants
	rule.AppendTimeFormatRFCshort(timefy.TimeRFC01T150405)

	// Rule.With creates a Timex with the rule's configuration
	tx := rule.With(time.Now())
	fmt.Println(tx.BeginningOfWeek())

	// Rule.Parse parses a string using the rule's configuration
	v, _ := rule.Parse("2025-11-12 22:14:01")
	fmt.Println(v)

	// Rule.MustParse panics on error
	v = rule.MustParse("2025-11-12 22:14:01")
	fmt.Println(v)
}
Contributing

To contribute to project, follow these steps:

  1. Clone the repository:

    git clone --depth 1 https://github.com/polarixa/timefy.git
    
  2. Navigate to the project directory:

    cd timefy
    
  3. Prepare the project environment:

    go mod tidy
    

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// TimeFormatRegexp is a regular expression that matches various time formats such as:
	// 	15:04:05, 15:04:05.000, 15:04:05.000000, 15, 2017-01-01 15:04, 2021-07-20T00:59:10Z,
	// 	2021-07-20T00:59:10+08:00, 2021-07-20T00:00:10-07:00, etc.
	TimeFormatRegexp = regexp.MustCompile(`(\s+|^\s*|T)\d{1,2}((:\d{1,2})*|((:\d{1,2}){2}\.(\d{3}|\d{6}|\d{9})))(\s*$|[Z+-])`)

	// TimeOnlyRegexp is a regular expression that matches time formats such as:
	// 	15:04:05, 15, 15:04:05.000, 15:04:05.000000, etc.
	TimeOnlyRegexp = regexp.MustCompile(`^\s*\d{1,2}((:\d{1,2})*|((:\d{1,2}){2}\.(\d{3}|\d{6}|\d{9})))\s*$`)
)
View Source
var (
	// TimeFormats is a slice of strings that holds various time format patterns.
	// These patterns can be used to parse and format time values in different layouts.
	TimeFormats = []string{
		"2006",
		"2006-1",
		"2006-1-2",
		"2006-1-2 15",
		"2006-1-2 15:4",
		"2006-1-2 15:4:5",
		"1-2",
		"15:4:5",
		"15:4",
		"15",
		"15:4:5 Jan 2, 2006 MST",
		"2006-01-02 15:04:05.999999999 -0700 MST",
		"2006-01-02T15:04:05Z0700",
		"2006-01-02T15:04:05Z07",
		"2006.1.2",
		"2006.1.2 15:04:05",
		"2006.01.02",
		"2006.01.02 15:04:05",
		"2006.01.02 15:04:05.999999999",
		"1/2/2006",
		"1/2/2006 15:4:5",
		"2006/01/02",
		"20060102",
		"2006/01/02 15:04:05",
		time.ANSIC,
		time.UnixDate,
		time.RubyDate,
		time.RFC822,
		time.RFC822Z,
		time.RFC850,
		time.RFC1123,
		time.RFC1123Z,
		time.RFC3339,
		time.RFC3339Nano,
		time.Kitchen,
		time.Stamp,
		time.StampMilli,
		time.StampMicro,
		time.StampNano,
	}
)
View Source
var WeekStartDay = time.Sunday

WeekStartDay is deprecated and provided for backward compatibility.

WARNING: Direct access to this variable is NOT thread-safe in concurrent code. For thread-safe access, use GetWeekStartDay() and SetWeekStartDay() instead.

Note: This variable is updated by SetWeekStartDay() for backward compatibility, but direct reads may race with concurrent SetWeekStartDay() calls.

Deprecated: Use GetWeekStartDay() and SetWeekStartDay() for thread-safe access.

Functions

func AddDay

func AddDay(v time.Time, day int) time.Time

AddDay takes a time value `v` and an integer `day` representing the number of days to add (or subtract if negative). It returns a new time.Time object that is adjusted by the specified number of days.

The function uses time.Add to add the given number of days to `v`. Since a day has 24 hours, it multiplies 24 by the number of days to convert the days into hours. If `day` is 0, the function simply returns the original time `v`.

Parameters:

  • `v`: A time.Time value representing the initial time

  • `day`: An integer representing the number of days to add. If negative, it subtracts the days from `v`.

Returns:

  • A time.Time value representing the time `v` adjusted by the specified number of days.

Example:

now := time.Now()
fiveDaysLater := AddDay(now, 5)  // This will return the time 5 days later.
fiveDaysEarlier := AddDay(now, -5) // This will return the time 5 days earlier.

func AddHour

func AddHour(v time.Time, hour int) time.Time

AddHour takes a time value `v` and an integer `hour` representing the number of hours to add (or subtract if negative). It returns a new time.Time object that is adjusted by the specified number of hours.

The function uses time.Add to add the given number of hours to `v`. If `hour` is 0, the function simply returns the original time `v`.

Parameters:

  • `v`: A time.Time value representing the initial time.

  • `hour`: An integer representing the number of hours to add. If negative, it subtracts the hours from `v`.

Returns:

  • A time.Time value representing the time `v` adjusted by the specified number of hours.

Example:

now := time.Now()
threeHoursLater := AddHour(now, 3)  // This will return the time 3 hours later.
threeHoursEarlier := AddHour(now, -3) // This will return the time 3 hours earlier.

func AddMinute

func AddMinute(v time.Time, minute int) time.Time

AddMinute takes a time value `v` and an integer `minute` representing the number of minutes to add (or subtract if negative). It returns a new time.Time object that is adjusted by the specified number of minutes.

The function uses time.Add to add the given number of minutes to `v`. If `minute` is 0, the function simply returns the original time `v`.

Parameters:

  • `v`: A time.Time value representing the initial time.

  • `minute`: An integer representing the number of minutes to add. If negative, it subtracts the minutes from `v`.

Returns:

  • A time.Time value representing the time `v` adjusted by the specified number of minutes.

Example:

now := time.Now()
tenMinutesLater := AddMinute(now, 10)  // This will return the time 10 minutes later.
tenMinutesEarlier := AddMinute(now, -10) // This will return the time 10 minutes earlier.

func AddSecond

func AddSecond(v time.Time, second int) time.Time

AddSecond takes a time value `v` and an integer `second` representing the number of seconds to add (or subtract if negative). It returns a new time.Time object that is adjusted by the specified number of seconds.

The function uses time.Add to add the given number of seconds to `v`. If `second` is 0, the function simply returns the original time `v`.

Parameters:

  • `v`: A time.Time value representing the initial time.

  • `second`: An integer representing the number of seconds to add. If negative, it subtracts the seconds from `v`.

Returns:

  • A time.Time value representing the time `v` adjusted by the specified number of seconds.

Example:

now := time.Now()

fiveSecondsLater := AddSecond(now, 5)  // This will return the time 5 seconds later.
fiveSecondsEarlier := AddSecond(now, -5) // This will return the time 5 seconds earlier.

func AdjustTimezone

func AdjustTimezone(v time.Time, tz string) time.Time

AdjustTimezone takes a time value `v` and a string `tz` representing the target timezone, and attempts to adjust `v` to the specified timezone. If the timezone conversion fails (due to an invalid timezone), the function returns the original time `v` without any changes.

The function internally calls SetTimezone to convert the time `v` to the specified timezone `tz`. If SetTimezone returns an error (e.g., if the timezone string is invalid), the function catches it and returns `v`. If no error occurs, it returns the adjusted time in the specified timezone.

Parameters:

  • `v`: A time.Time value representing the reference time.

  • `tz`: A string representing the IANA timezone name (e.g., "America/New_York", "Asia/Tokyo").

Returns:

  • A time.Time value representing the time `v` adjusted to the specified timezone. If an error occurs, it returns the original time.

Example:

now := time.Now()
adjustedTime := AdjustTimezone(now, "Europe/Paris") // This will adjust `now` to Paris' timezone if valid, or return `now` if invalid.

func BeginOfDay

func BeginOfDay(v time.Time) time.Time

BeginOfDay takes a time value `v` and returns a new time.Time object representing the beginning of the day for that date.

The function uses the time.Date method to set the time to midnight (00:00:00) while keeping the year, month, and day values from the input time `v`. The location (timezone) of the returned time is the same as the input time.

Parameters:

  • `v`: A time.Time value representing the date from which the beginning of the day is extracted.

Returns:

  • A time.Time value representing the start of the day (00:00:00) for the provided date.

Example:

now := time.Now()
startOfDay := BeginOfDay(now) // This will set the time to midnight of the current day.

func BeginningOfDay

func BeginningOfDay() time.Time

BeginningOfDay returns the current time rounded down to the beginning of the current day. This function resets the hour, minute, second, and nanosecond components of the time to zero, providing a time value that represents the exact start of the day (midnight).

It utilizes the With() function to obtain the current time and then applies the BeginningOfDay() method to achieve this rounding.

Returns:

  • A time.Time value representing the start of the current day (e.g., 00:00:00).

Example:

beginning := BeginningOfDay() // This will return the current time set to the start of the day (e.g., 2023-10-25 00:00:00).

func BeginningOfHour

func BeginningOfHour() time.Time

BeginningOfHour returns the current time rounded down to the beginning of the current hour. This function resets the minute, second, and nanosecond components of the time to zero, providing a time value that represents the exact start of the hour.

It utilizes the With() function to obtain the current time and then applies the BeginningOfHour() method to round it down.

Returns:

  • A time.Time value representing the start of the current hour.

Example:

beginning := BeginningOfHour() // This will return the current time set to the start of the hour (e.g., 12:00:00).

func BeginningOfMinute

func BeginningOfMinute() time.Time

BeginningOfMinute returns the current time rounded down to the beginning of the current minute. It utilizes the With() function to achieve this. The resulting time will have seconds and nanoseconds set to zero.

Returns:

  • A time.Time value representing the start of the current minute.

Example:

beginning := BeginningOfMinute() // This will return the current time set to the start of the minute (e.g., 12:30:00).

func BeginningOfMonth

func BeginningOfMonth() time.Time

BeginningOfMonth returns the current time rounded down to the beginning of the current month. This function resets the day, hour, minute, second, and nanosecond components of the time to zero, providing a time value that represents the exact start of the month (the first day at midnight).

It utilizes the With() function to obtain the current time and then applies the BeginningOfMonth() method to achieve this rounding.

Returns:

  • A time.Time value representing the start of the current month (e.g., 2023-10-01 00:00:00).

Example:

beginning := BeginningOfMonth() // This will return the current time set to the start of the month (e.g., 2023-10-01 00:00:00).

func BeginningOfQuarter

func BeginningOfQuarter() time.Time

BeginningOfQuarter returns the current time rounded down to the beginning of the current quarter. A quarter is a three-month period within the year, specifically:

  • Q1: January to March
  • Q2: April to June
  • Q3: July to September
  • Q4: October to December

This function resets the day, hour, minute, second, and nanosecond components of the time to zero, providing a time value that represents the exact start of the current quarter (the first day of the quarter at midnight).

It utilizes the With() function to obtain the current time and then applies the BeginningOfQuarter() method to achieve this rounding.

Returns:

  • A time.Time value representing the start of the current quarter (e.g., 2023-10-01 00:00:00 if the current date is in Q4).

Example:

beginning := BeginningOfQuarter() // This will return the current time set to the start of the current quarter (e.g., 2023-10-01 00:00:00 if it's the fourth quarter).

func BeginningOfWeek

func BeginningOfWeek() time.Time

BeginningOfWeek returns the current time rounded down to the beginning of the current week. This function resets the hour, minute, second, and nanosecond components of the time to zero, providing a time value that represents the exact start of the week (usually Sunday or Monday depending on the locale).

It utilizes the With() function to obtain the current time and then applies the BeginningOfWeek() method to achieve this rounding.

Returns:

  • A time.Time value representing the start of the current week (e.g., 00:00:00 on the first day of the week).

Example:

beginning := BeginningOfWeek() // This will return the current time set to the start of the week (e.g., 2023-10-22 00:00:00 if Sunday is the start of the week).

func BeginningOfYear

func BeginningOfYear() time.Time

BeginningOfYear returns the current time rounded down to the beginning of the current year. This function resets the month, day, hour, minute, second, and nanosecond components of the time to zero, providing a time value that represents the exact start of the year (January 1st at midnight).

It utilizes the With() function to obtain the current time and then applies the BeginningOfYear() method to achieve this rounding.

Returns:

  • A time.Time value representing the start of the current year (e.g., 2023-01-01 00:00:00).

Example:

beginning := BeginningOfYear() // This will return the current time set to the start of the year (e.g., 2023-01-01 00:00:00).

func Between

func Between(time1, time2 string) bool

Between takes two string inputs representing time values and checks if the current time falls within the range defined by those two times. This function utilizes the With() function to obtain the current time as a reference point and then applies the Between() method to evaluate the range.

The function assumes that the provided time strings are in a valid format. If the current time is greater than or equal to time1 and less than or equal to time2, it returns true; otherwise, it returns false.

Parameters:

  • time1: A string representing the start of the time range.
  • time2: A string representing the end of the time range.

Returns:

  • A boolean value indicating whether the current time is within the specified range (inclusive).

Example:

isWithin := Between("2023-10-20", "2023-10-30") // This will return true if the current time is between these two dates.
isWithin := Between("2023-10-25", "2023-10-26") // This will return true if the current date is exactly 2023-10-25.

func DefaultFormatRFC

func DefaultFormatRFC() string

DefaultFormatRFC formats the current time using the default layout.

Returns:

  • A string representing the formatted time.

Example:

formatted := DefaultFormatRFC() // Returns the formatted current time in the default format.

func EndOfDay

func EndOfDay() time.Time

EndOfDay returns the current time rounded up to the end of the current day. This function resets the hour, minute, second, and nanosecond components of the time to zero and then adds one day, providing a time value that represents the last moment of the current day (23 hours, 59 minutes, 59 seconds, and 999999999 nanoseconds).

It utilizes the With() function to obtain the current time and then applies the EndOfDay() method to achieve this rounding.

Returns:

  • A time.Time value representing the end of the current day (e.g., 2023-10-25 23:59:59.999999999).

Example:

end := EndOfDay() // This will return the current time set to the end of the day (e.g., 2023-10-25 23:59:59.999999999).

func EndOfHour

func EndOfHour() time.Time

EndOfHour returns the current time rounded up to the end of the current hour. This function resets the minute, second, and nanosecond components of the time to zero and then adds one hour, providing a time value that represents the last moment of the current hour (59 minutes, 59 seconds, and 999999999 nanoseconds).

It utilizes the With() function to obtain the current time and then applies the EndOfHour() method to achieve this rounding.

Returns:

  • A time.Time value representing the end of the current hour (e.g., 12:59:59.999999999).

Example:

end := EndOfHour() // This will return the current time set to the end of the hour (e.g., 12:59:59.999999999).

func EndOfMinute

func EndOfMinute() time.Time

EndOfMinute returns the current time rounded up to the end of the current minute. This function resets the second and nanosecond components of the time to zero and then adds one minute, providing a time value that represents the last moment of the current minute (59 seconds and 999999999 nanoseconds).

It utilizes the With() function to obtain the current time and then applies the EndOfMinute() method to achieve this rounding.

Returns:

  • A time.Time value representing the end of the current minute (e.g., 12:30:59.999999999).

Example:

end := EndOfMinute() // This will return the current time set to the end of the minute (e.g., 12:30:59.999999999).

func EndOfMonth

func EndOfMonth() time.Time

EndOfMonth returns the current time rounded up to the end of the current month. This function resets the day, hour, minute, second, and nanosecond components of the time to zero and then adds one month, providing a time value that represents the last moment of the current month (e.g., 23 hours, 59 minutes, 59 seconds, and 999999999 nanoseconds) on the last day of the month.

It utilizes the With() function to obtain the current time and then applies the EndOfMonth() method to achieve this rounding.

Returns:

  • A time.Time value representing the end of the current month (e.g., 2023-10-31 23:59:59.999999999).

Example:

end := EndOfMonth() // This will return the current time set to the end of the month (e.g., 2023-10-31 23:59:59.999999999).

func EndOfQuarter

func EndOfQuarter() time.Time

EndOfQuarter returns the current time rounded up to the end of the current quarter. A quarter is defined as a three-month period within the year, specifically:

  • Q1: January to March
  • Q2: April to June
  • Q3: July to September
  • Q4: October to December

This function resets the day, hour, minute, second, and nanosecond components of the time to zero and then adds the number of months needed to reach the first day of the next quarter, providing a time value that represents the last moment of the current quarter (e.g., 23 hours, 59 minutes, 59 seconds, and 999999999 nanoseconds) on the last day of the quarter.

It utilizes the With() function to obtain the current time and then applies the EndOfQuarter() method to achieve this rounding.

Returns:

  • A time.Time value representing the end of the current quarter (e.g., 2023-03-31 23:59:59.999999999 if the current date is in Q1).

Example:

end := EndOfQuarter() // This will return the current time set to the end of the current quarter (e.g., 2023-12-31 23:59:59.999999999 if it's the fourth quarter).

func EndOfSunday

func EndOfSunday() time.Time

EndOfSunday returns the date and time representing the end of the most recent or upcoming Sunday relative to the current time. This function resets the time to 23 hours, 59 minutes, 59 seconds, and 999999999 nanoseconds, providing a time value that represents the last moment of Sunday.

It utilizes the With() function to obtain the current time and then applies the EndOfSunday() method to achieve this rounding.

Returns:

  • A time.Time value representing the end of the most recent or upcoming Sunday based on the current date and time (e.g., 2023-10-29 23:59:59.999999999 if the current date is within that week).

Example:

end := EndOfSunday() // This will return the date and time set to the end of the next Sunday (e.g., 2023-10-29 23:59:59.999999999).

func EndOfWeek

func EndOfWeek() time.Time

EndOfWeek returns the current time rounded up to the end of the current week. This function resets the hour, minute, second, and nanosecond components of the time to zero and then adds one week, providing a time value that represents the last moment of the current week (e.g., 23 hours, 59 minutes, 59 seconds, and 999999999 nanoseconds) on the last day of the week (usually Saturday or Sunday, depending on the locale).

It utilizes the With() function to obtain the current time and then applies the EndOfWeek() method to achieve this rounding.

Returns:

  • A time.Time value representing the end of the current week (e.g., 2023-10-29 23:59:59.999999999 if Sunday is the last day of the week).

Example:

end := EndOfWeek() // This will return the current time set to the end of the week (e.g., 2023-10-29 23:59:59.999999999).

func EndOfYear

func EndOfYear() time.Time

EndOfYear returns the current time rounded up to the end of the current year. This function resets the month, day, hour, minute, second, and nanosecond components of the time to zero and then adds one year, providing a time value that represents the last moment of the current year (e.g., 23 hours, 59 minutes, 59 seconds, and 999999999 nanoseconds) on December 31st.

It utilizes the With() function to obtain the current time and then applies the EndOfYear() method to achieve this rounding.

Returns:

  • A time.Time value representing the end of the current year (e.g., 2023-12-31 23:59:59.999999999).

Example:

end := EndOfYear() // This will return the current time set to the end of the current year (e.g., 2023-12-31 23:59:59.999999999).

func FDefaultFormatRFC

func FDefaultFormatRFC(v time.Time) string

DefaultFormatRFC formats the time using the default layout.

Parameters:

  • `v`: A time.Time value representing the time to format.

Returns:

  • A string representing the formatted time.

Example:

v := time.Date(2023, time.August, 15, 13, 45, 30, 0, time.UTC)
formatted := DefaultFormatRFC(v) // Returns the formatted time in the default format.

func FEndOfDay

func FEndOfDay(v time.Time) time.Time

FEndOfDay takes a time value `v` and returns a new time.Time object representing the end of the day for that date.

The function uses the time.Date method to set the time to the last possible second (23:59:59) of the provided day. It maintains the same year, month, and day values from the input time `v`. The location (timezone) of the returned time is the same as the input time.

Parameters:

  • `v`: A time.Time value representing the date from which the end of the day is extracted.

Returns:

  • A time.Time value representing the end of the day (23:59:59) for the provided date.

Example:

now := time.Now()
endOfDay := FEndOfDay(now) // This will set the time to the last second of the current day.

func FFormatRFC

func FFormatRFC(v time.Time, layout TimeFormatRFC) string

FormatRFC formats the time using the provided layout.

Parameters:

  • `v`: A time.Time value representing the time to format.
  • `layout`: A TimeFormatRFC value representing the layout to use for formatting.

Returns:

  • A string representing the formatted time.

Example:

formatted := FormatRFC(v, TimeFormat20060102T150405) // Returns the formatted time in the format "2023-08-15 13:45:30".

func FFormatRFCshort

func FFormatRFCshort(v time.Time, layout TimeRFC) string

FormatRFCshort formats the time using the provided layout.

Parameters:

  • `v`: A time.Time value representing the time to format.
  • `layout`: A TimeRFC value representing the layout to use for formatting.

Returns:

  • A string representing the formatted time.

Example:

formatted := FormatRFCshort(v, TimeRFC01T150405) // Returns the formatted time in the format "13:45:30".

func FormatRFC

func FormatRFC(layout TimeFormatRFC) string

FormatRFC formats the time using the provided layout.

Parameters:

  • `layout`: A TimeFormatRFC value representing the layout to use for formatting.

Returns:

  • A string representing the formatted time.

Example:

formatted := FormatRFC(TimeFormat20060102T150405) // Returns the formatted time in the format "2023-08-15 13:45:30".

func FormatRFCshort

func FormatRFCshort(layout TimeRFC) string

FormatRFCshort formats the time using the provided layout.

Parameters:

  • `layout`: A TimeRFC value representing the layout to use for formatting.

Returns:

  • A string representing the formatted time.

Example:

formatted := FormatRFCshort(TimeRFC01T150405) // Returns the formatted time in the format "13:45:30".

func FormatTimex

func FormatTimex(t time.Time) []int

FormatTimex converts a given time.Time value into a slice of integers representing various time components.

The function extracts the hour, minute, second, nanosecond, day, month, and year from the provided time.Time value. It then returns these components in a specific order as a slice of integers.

The order of the returned slice is as follows:

  • [0]: Nanosecond
  • [1]: Second
  • [2]: Minute
  • [3]: Hour
  • [4]: Day
  • [5]: Month (as an integer, where January is 1)
  • [6]: Year

Parameters:

  • `t`: A time.Time value representing the time to format.

Returns:

  • A slice of integers containing the nanosecond, second, minute, hour, day, month, and year components of the provided time.Time value.

Example:

t := time.Date(2023, time.March, 15, 8, 0, 0, 0, time.UTC)
formatted := FormatTimex(t) // This will return a slice with the components [0, 0, 0, 8, 15, 3, 2023].

func Friday

func Friday(s ...string) time.Time

Friday returns the date and time of the most recent or upcoming Friday relative to the current time. This function can take an optional string parameter to specify the desired format for the output, but it defaults to the standard representation of time if no arguments are provided.

It utilizes the With() function to obtain the current time and then applies the Friday() method to determine the appropriate Friday date and time.

Returns:

  • A time.Time value representing the most recent or upcoming Friday based on the current date and time. The output can vary depending on the optional format parameter.

Example:

friday := Friday() // This will return the date and time for the next upcoming Friday (e.g., 2023-11-03 00:00:00).
fridayFormatted := Friday("2006-01-02") // This will return the next Friday formatted as "YYYY-MM-DD".

func GetWeekStartDay

func GetWeekStartDay() time.Weekday

GetWeekStartDay returns the current default week start day in a thread-safe manner.

func GetWeekdaysInRange

func GetWeekdaysInRange(start time.Time, end time.Time) []time.Time

GetWeekdaysInRange returns a slice of time.Time objects representing all weekdays (Monday to Friday) between the specified start and end dates, inclusive.

The function iterates through each date from `start` to `end`, checking if each date is a weekday. It excludes Saturdays and Sundays. It also handles leap years correctly by ensuring that February 29 is included only in leap years. If the year is not a leap year, it checks if the day is valid for the month.

Parameters:

  • `start`: A time.Time value representing the start date of the range.

  • `end`: A time.Time value representing the end date of the range.

Returns:

  • A slice of time.Time values representing all weekdays between `start` and `end`, inclusive.

Example:

start := time.Date(2023, time.March, 1, 0, 0, 0, 0, time.UTC)
end := time.Date(2023, time.March, 10, 0, 0, 0, 0, time.UTC)
weekdays := GetWeekdaysInRange(start, end) // This will return all weekdays between March 1 and March 10, 2023.

func IsLeapYear

func IsLeapYear(year int) bool

IsLeapYear determines if the specified year is a leap year.

A year is considered a leap year if:

  • It is divisible by 4; and
  • It is not divisible by 100, unless it is also divisible by 400.

Parameters:

  • `year`: An integer representing the year to check.

Returns: - A boolean value:

  • true if the specified year is a leap year;
  • false otherwise.

Example:

leapYear := IsLeapYear(2020) // This will return true since 2020 is a leap year.
nonLeapYear := IsLeapYear(2021) // This will return false since 2021 is not a leap year.

func IsLeapYearN

func IsLeapYearN(v time.Time) bool

IsLeapYearN checks if the year of the provided time value `v` is a leap year.

The function retrieves the year from the time.Time object using the Year() method and calls IsLeapYear to determine if that year is a leap year.

Parameters:

  • `v`: A time.Time value representing the date from which the year is extracted.

Returns: - A boolean value:

  • true if the year from the date `v` is a leap year;
  • false otherwise.

Example:

now := time.Now()
isLeap := IsLeapYearN(now) // This will return true if the current year is a leap year.

func IsWithinTolerance

func IsWithinTolerance(v time.Time) bool

IsWithinTolerance checks if the provided time `v` is within a one-minute tolerance window around the current time.

The function calculates the difference between the provided time `v` and the current time using time.Sub. It then checks if the difference is within a range of plus or minus one minute (`tolerance`). If the difference falls within this range, the function returns true, indicating that `v` is within the tolerance window. Otherwise, it returns false.

Parameters:

  • `v`: A time.Time value representing the time to check.

Returns:

- A boolean value:

  • true if `v` is within one minute (before or after) the current time;

  • false if `v` is outside this one-minute window.

Example:

now := time.Now()
checkTime := now.Add(time.Second * 30)
isOnTime := IsWithinTolerance(checkTime) // This will return true since checkTime is within 1 minute of now.

func Monday

func Monday(s ...string) time.Time

Monday returns the date and time of the most recent or upcoming Monday relative to the current time. This function can take an optional string parameter to specify the desired format for the output, but it defaults to the standard representation of time if no arguments are provided.

It utilizes the With() function to obtain the current time and then applies the Monday() method to determine the appropriate Monday date and time.

Returns:

  • A time.Time value representing the most recent or upcoming Monday based on the current date and time. The output can vary depending on the optional format parameter.

Example:

monday := Monday() // This will return the date and time for the next upcoming Monday (e.g., 2023-10-30 00:00:00).
mondayFormatted := Monday("2006-01-02") // This will return the next Monday formatted as "YYYY-MM-DD".

func MustParse

func MustParse(s ...string) time.Time

MustParse takes a variable number of string inputs and attempts to parse them into a time.Time value. This function uses the With() function to obtain the current time as a reference point and then applies the MustParse() method to interpret the provided string(s) as time.

Unlike the Parse function, MustParse will panic if the parsing fails, making it suitable for scenarios where a valid time is expected and errors are not anticipated. If the input strings are in valid formats, it returns the corresponding time.Time value.

Parameters:

  • s: A variadic parameter that accepts one or more strings to be parsed into a time.Time value.

Returns:

  • A time.Time value representing the parsed time if successful.
  • This function does not return an error; instead, it will panic if parsing fails.

Example:

timeValue := MustParse("2023-10-25") // This will return the parsed time if the input string is in a valid format.
// If the input is invalid, it will cause a panic.

func MustParseInLocation

func MustParseInLocation(loc *time.Location, s ...string) time.Time

MustParseInLocation takes a variable number of string inputs and attempts to parse them into a time.Time value based on a specified time zone location. This function utilizes the With() function to obtain the current time in the provided location as a reference point and then applies the MustParse() method to interpret the provided string(s) as time.

Similar to MustParse, this function will panic if the parsing fails, making it suitable for scenarios where a valid time is expected and errors are not anticipated. If the input strings are in valid formats, it returns the corresponding time.Time value adjusted to the specified location.

Parameters:

  • loc: A pointer to a time.Location struct that specifies the desired time zone for parsing.
  • s: A variadic parameter that accepts one or more strings to be parsed into a time.Time value.

Returns:

  • A time.Time value representing the parsed time in the specified location if successful.
  • This function does not return an error; instead, it will panic if parsing fails.

Example:

timeValue := MustParseInLocation(time.UTC, "2023-10-25") // This will return the parsed time in UTC if the input string is in a valid format.
// If the input is invalid, it will cause a panic.

func Parse

func Parse(s ...string) (time.Time, error)

Parse takes a variable number of string inputs and attempts to parse them into a time.Time value. This function uses the With() function to obtain the current time as a reference point and then applies the Parse() method to interpret the provided string(s) as time.

The function can handle multiple formats and will return the first successfully parsed time value along with any potential error encountered during parsing.

Returns:

  • A time.Time value representing the parsed time if successful.
  • An error indicating any issues encountered during the parsing process, or nil if parsing was successful.

Example:

timeValue, err := Parse("2023-10-25") // This will return the parsed time if the input string is in a valid format.
if err != nil {
	// Handle the parsing error
}

func ParseInLocation

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

ParseInLocation takes a variable number of string inputs and attempts to parse them into a time.Time value based on a specified time zone location. This function utilizes the With() function to obtain the current time in the provided location as a reference point and then applies the Parse() method to interpret the provided string(s) as time.

The function can handle multiple formats and will return the first successfully parsed time value in the specified location, along with any potential error encountered during parsing.

Parameters:

  • loc: A pointer to a time.Location struct that specifies the desired time zone for parsing.
  • s: A variadic parameter that accepts one or more strings to be parsed into a time.Time value.

Returns:

  • A time.Time value representing the parsed time in the specified location if successful.
  • An error indicating any issues encountered during the parsing process, or nil if parsing was successful.

Example:

timeValue, err := ParseInLocation(time.UTC, "2023-10-25") // This will return the parsed time in UTC if the input string is in a valid format.
if err != nil {
	// Handle the parsing error
}

func PrevBeginOfDay

func PrevBeginOfDay(v time.Time, day int) time.Time

PrevBeginOfDay takes a time value `v` and an integer `day` representing the number of days to go back. It returns a new time.Time object representing the beginning of the day for the date `day` days before the given date.

The function subtracts `day` days from the input time `v` using the time.AddDate method and then calls BeginOfDay on the resulting time to set the time to midnight (00:00:00) for that earlier date.

Parameters:

  • `v`: A time.Time value representing the reference date.

  • `day`: An integer representing how many days to go back from the reference date.

Returns:

  • A time.Time value representing the start of the day (00:00:00) for the date that is `day` days before `v`.

Example:

now := time.Now()
twoDaysAgoStart := PrevBeginOfDay(now, 2) // This will return the start of the day two days before the current date.

func PrevEndOfDay

func PrevEndOfDay(v time.Time, day int) time.Time

PrevEndOfDay takes a time value `v` and an integer `day` representing the number of days to go back. It returns a new time.Time object representing the end of the day for the date `day` days before the given date.

The function subtracts `day` days from the input time `v` using the time.AddDate method and then calls EndOfDayX on the resulting time to set the time to the last second (23:59:59) of that earlier date.

Parameters:

  • `v`: A time.Time value representing the reference date.

  • `day`: An integer representing how many days to go back from the reference date.

Returns:

  • A time.Time value representing the end of the day (23:59:59) for the date that is `day` days before `v`.

Example:

now := time.Now()
twoDaysAgoEnd := PrevEndOfDay(now, 2) // This will return the end of the day two days before the current date.

func Quarter

func Quarter() uint

Quarter returns the current quarter of the year based on the current date and time. A quarter is defined as a three-month period within the year, specifically:

  • Q1: January to March
  • Q2: April to June
  • Q3: July to September
  • Q4: October to December

This function utilizes the With() function to obtain the current time and then applies the Quarter() method to determine the current quarter.

Returns:

  • A uint value representing the current quarter of the year (1, 2, 3, or 4).

Example:

quarter := Quarter() // This will return the current quarter (e.g., 4 for October).

func Saturday

func Saturday(s ...string) time.Time

Saturday returns the date and time of the most recent or upcoming Saturday relative to the current time. This function can take an optional string parameter to specify the desired format for the output, but it defaults to the standard representation of time if no arguments are provided.

It utilizes the With() function to obtain the current time and then applies the Saturday() method to determine the appropriate Saturday date and time.

Returns:

  • A time.Time value representing the most recent or upcoming Saturday based on the current date and time. The output can vary depending on the optional format parameter.

Example:

friday := Friday() // This will return the date and time for the next upcoming Friday (e.g., 2023-11-03 00:00:00).
fridayFormatted := Friday("2006-01-02") // This will return the next Friday formatted as "YYYY-MM-DD".

func SetTimezone

func SetTimezone(v time.Time, tz string) (time.Time, error)

SetTimezone takes a time value `v` and a string `tz` representing the target timezone. It returns a new time.Time object with the same time as `v` but converted to the specified timezone `tz`.

The function uses time.LoadLocation to load the location based on the timezone string `tz`. It then converts the input time `v` to the specified timezone using the time.In method. If an error occurs while loading the timezone (for example, if the timezone string is invalid), the function returns the current time value in UTC along with the error.

Parameters:

  • `v`: A time.Time value representing the reference time.

  • `tz`: A string representing the IANA timezone name (e.g., "America/New_York", "Europe/London").

Returns:

  • A time.Time value representing the time `v` converted to the specified timezone.

  • An error value, which will be non-nil if the timezone string is invalid.

Example:

now := time.Now()
nyTime, err := SetTimezone(now, "America/New_York") // This will convert the current time to New York's timezone.

func SetWeekStartDay

func SetWeekStartDay(day time.Weekday)

SetWeekStartDay sets the default week start day in a thread-safe manner.

Note: This function also updates the deprecated WeekStartDay variable for backward compatibility. However, direct reads from WeekStartDay are not protected by the mutex. Use GetWeekStartDay() for thread-safe reads.

func SinceHour

func SinceHour(v time.Time) float64

SinceHour calculates the number of hours that have passed since the provided time value `v`.

The function computes the time difference between the current time and `v` using time.Since(). The resulting duration is then converted into hours using the Hours() method.

Parameters:

  • `v`: A time.Time value representing the starting time to calculate the elapsed hours from.

Returns:

  • A float64 value representing the number of hours that have passed since the time `v`.

Example:

start := time.Date(2023, time.March, 15, 8, 0, 0, 0, time.UTC)
elapsedHours := SinceHour(start) // This will return the hours passed since March 15, 2023, 8:00 AM.

func SinceMinute

func SinceMinute(v time.Time) float64

SinceMinute calculates the number of minutes that have passed since the provided time value `v`.

The function computes the time difference between the current time and `v` using time.Since(). The resulting duration is then converted into minutes using the Minutes() method.

Parameters:

  • `v`: A time.Time value representing the starting time to calculate the elapsed minutes from.

Returns:

  • A float64 value representing the number of minutes that have passed since the time `v`.

Example:

start := time.Date(2023, time.March, 15, 8, 0, 0, 0, time.UTC)
elapsedMinutes := SinceMinute(start) // This will return the minutes passed since March 15, 2023, 8:00 AM.

func SinceSecond

func SinceSecond(v time.Time) float64

SinceSecond calculates the number of seconds that have passed since the provided time value `v`.

The function computes the time difference between the current time and `v` using time.Since(). The resulting duration is then converted into seconds using the Seconds() method.

Parameters:

  • `v`: A time.Time value representing the starting time to calculate the elapsed seconds from.

Returns:

  • A float64 value representing the number of seconds that have passed since the time `v`.

Example:

start := time.Date(2023, time.March, 15, 8, 0, 0, 0, time.UTC)
elapsedSeconds := SinceSecond(start) // This will return the seconds passed since March 15, 2023, 8:00 AM.

func Sunday

func Sunday(s ...string) time.Time

Sunday returns the date and time of the most recent or upcoming Sunday relative to the current time. This function can take an optional string parameter to specify the desired format for the output, but it defaults to the standard representation of time if no arguments are provided.

It utilizes the With() function to obtain the current time and then applies the Sunday() method to determine the appropriate Sunday date and time.

Returns:

  • A time.Time value representing the most recent or upcoming Sunday based on the current date and time. The output can vary depending on the optional format parameter.

Example:

sunday := Sunday() // This will return the date and time for the next upcoming Sunday (e.g., 2023-10-29 00:00:00).
sundayFormatted := Sunday("2006-01-02") // This will return the next Sunday formatted as "YYYY-MM-DD".

func Thursday

func Thursday(s ...string) time.Time

Thursday returns the date and time of the most recent or upcoming Thursday relative to the current time. This function can take an optional string parameter to specify the desired format for the output, but it defaults to the standard representation of time if no arguments are provided.

It utilizes the With() function to obtain the current time and then applies the Thursday() method to determine the appropriate Thursday date and time.

Returns:

  • A time.Time value representing the most recent or upcoming Thursday based on the current date and time. The output can vary depending on the optional format parameter.

Example:

thursday := Thursday() // This will return the date and time for the next upcoming Thursday (e.g., 2023-11-02 00:00:00).
thursdayFormatted := Thursday("2006-01-02") // This will return the next Thursday formatted as "YYYY-MM-DD".

func Tuesday

func Tuesday(s ...string) time.Time

Tuesday returns the date and time of the most recent or upcoming Tuesday relative to the current time. This function can take an optional string parameter to specify the desired format for the output, but it defaults to the standard representation of time if no arguments are provided.

It utilizes the With() function to obtain the current time and then applies the Tuesday() method to determine the appropriate Tuesday date and time.

Returns:

  • A time.Time value representing the most recent or upcoming Tuesday based on the current date and time. The output can vary depending on the optional format parameter.

Example:

tuesday := Tuesday() // This will return the date and time for the next upcoming Tuesday (e.g., 2023-10-31 00:00:00).
tuesdayFormatted := Tuesday("2006-01-02") // This will return the next Tuesday formatted as "YYYY-MM-DD".

func Wednesday

func Wednesday(s ...string) time.Time

Wednesday returns the date and time of the most recent or upcoming Wednesday relative to the current time. This function can take an optional string parameter to specify the desired format for the output, but it defaults to the standard representation of time if no arguments are provided.

It utilizes the With() function to obtain the current time and then applies the Wednesday() method to determine the appropriate Wednesday date and time.

Returns:

  • A time.Time value representing the most recent or upcoming Wednesday based on the current date and time. The output can vary depending on the optional format parameter.

Example:

wednesday := Wednesday() // This will return the date and time for the next upcoming Wednesday (e.g., 2023-11-01 00:00:00).
wednesdayFormatted := Wednesday("2006-01-02") // This will return the next Wednesday formatted as "YYYY-MM-DD".

Types

type Rule

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

Rule rule for timefy weekStartDay set week start day, default is sunday timeLocation set time location, default is local timeFormats set time formats, default is []string{"2006-01-02 15:04:05"}

func NewRule

func NewRule() *Rule

NewRule creates a new rule with the default configuration.

Returns:

  • A pointer to a `Config` struct, which includes the default configuration.

Example:

rule := NewRule() // This creates a new rule with the default configuration.
rule.WithWeekStartDay(time.Monday) // This sets the week start day to Monday.
rule.WithTimeFormats([]string{"2006-01-02 15:04:05"}) // This sets the time formats to the default time formats.
rule.WithLocation(time.UTC) // This sets the time location to UTC.
return rule

func (*Rule) AppendTimeFormat

func (c *Rule) AppendTimeFormat(format ...string) *Rule

AppendTimeFormat appends the time formats.

Parameters:

  • `format`: A variadic list of strings representing the time formats to append.

Returns:

  • A pointer to a `Rule` struct, which includes the updated configuration.

Example:

rule := NewRule() // This creates a new rule with the default configuration.
rule.AppendTimeFormat("2006-01-02 15:04:05") // This appends the time format "2006-01-02 15:04:05".
return rule

func (*Rule) AppendTimeFormatRFC

func (c *Rule) AppendTimeFormatRFC(format ...TimeFormatRFC) *Rule

AppendTimeFormatRFC appends the time formats RFC.

Parameters:

  • `format`: A variadic list of TimeFormatRFC values representing the time formats to append.

Returns:

  • A pointer to a `Rule` struct, which includes the updated configuration.

Example:

rule := NewRule() // This creates a new rule with the default configuration.
rule.AppendTimeFormatRFC(TimeFormat20060102T150405999999, TimeFormat20060102T150405) // This appends the time formats "2006-01-02T15:04:05.999999" and "2006-01-02T15:04:05".
return rule

func (*Rule) AppendTimeFormatRFCshort

func (c *Rule) AppendTimeFormatRFCshort(format ...TimeRFC) *Rule

AppendTimeFormatRFCshort appends the time formats RFC short.

Parameters:

  • `format`: A variadic list of strings representing the time formats to append.

Returns:

  • A pointer to a `Rule` struct, which includes the updated configuration.

Example:

rule := NewRule() // This creates a new rule with the default configuration.
rule.AppendTimeFormatRFCshort(TimeRFC01T150405) // This appends the time format "15:04:05".
return rule

func (*Rule) ApplyLocalLoc

func (c *Rule) ApplyLocalLoc() *Rule

ApplyLocalLoc applies the local location to the configuration.

Returns:

  • A pointer to a `Config` struct, which includes the updated configuration.

Example:

rule := NewRule() // This creates a new rule with the default configuration.
rule.ApplyLocalLoc() // This sets the time location to local.
return rule

func (*Rule) ApplyUTCLoc

func (c *Rule) ApplyUTCLoc() *Rule

ApplyUTCLoc applies the UTC location to the configuration.

Returns:

  • A pointer to a `Config` struct, which includes the updated configuration.

Example:

rule := NewRule() // This creates a new rule with the default configuration.
rule.ApplyUTCLoc() // This sets the time location to UTC.
return rule

func (*Rule) MustParse

func (c *Rule) MustParse(s ...string) time.Time

MustParse attempts to parse a given set of string representations of time using the current `Config`, and panics if parsing fails.

This function checks if the `TimeLocation` field in the configuration `c` is set. If it is not set, it uses the system's local time zone for parsing. If `TimeLocation` is set, it utilizes the specified location to interpret the time. The actual parsing task is delegated to the `MustParse()` method of a new `Timex` object created using `With()`, which wraps the current time with the existing configuration.

Parameters:

  • `s`: A variadic list of strings representing dates or times to be parsed.

Returns:

  • A `time.Time` value representing the parsed time. This function will panic if parsing fails.

Example:

config := &Config{TimeLocation: time.UTC}
parsedTime := config.MustParse("2023-10-24T12:00:00Z") // Parses the string using UTC time location.

 If no `TimeLocation` is set, the function uses the local time zone:

config := &Config{}
parsedTime := config.MustParse("2023-10-24T12:00:00") // Parses using the local time zone, panicking on failure.

func (*Rule) Parse

func (c *Rule) Parse(s ...string) (time.Time, error)

Parse attempts to parse a given set of string representations of time using the current `Config`.

The function checks whether the `TimeLocation` field in the configuration `c` is set. If it is not set, the function defaults to parsing the strings based on the current time (using the system's local time zone). If `TimeLocation` is set, it uses the specified location to interpret the time. It delegates the parsing task to the `Parse()` method of a new `Timex` object created using `With()`, which wraps the current time with the existing configuration.

Parameters:

  • `s`: A variadic list of strings representing dates or times to be parsed.

Returns:

  • A `time.Time` value if one of the provided strings is successfully parsed.
  • An error if parsing fails.

Example:

config := &Config{TimeLocation: time.UTC}
parsedTime, err := config.Parse("2023-10-24T12:00:00Z") // Parses the string using UTC time location.

If no `TimeLocation` is set, the function uses the local time zone:

config := &Config{}
parsedTime, err := config.Parse("2023-10-24T12:00:00") // Parses using the local time zone.

func (*Rule) With

func (c *Rule) With(v time.Time) *Timex

With wraps the provided time value `v` into a Timex object using the current configuration `c`.

This method is called on a `Config` object to create a new `Timex` instance, where the provided time and the configuration are bundled together. Unlike the global `With()` function, this method uses the specific configuration tied to the `Config` instance `c`.

Parameters:

  • `v`: A time.Time value representing the time to be wrapped inside the Timex struct.

Returns:

  • A pointer to a `Timex` struct, which includes the provided time and the specific `Config` instance.

Example:

customConfig := &Config{WeekStartDay: time.Monday}
t := time.Now()
timex := customConfig.With(t) // This creates a Timex object with the custom configuration.

func (*Rule) WithLocation

func (c *Rule) WithLocation(location *time.Location) *Rule

WithLocation sets the time location.

Parameters:

  • `timeLocation`: A pointer to a time.Location value representing the time location.

Returns:

  • A pointer to a `Config` struct, which includes the updated configuration.

Example:

rule := NewRule() // This creates a new rule with the default configuration.
rule.WithLocation(time.UTC) // This sets the time location to UTC.
return rule

func (*Rule) WithLocationRFC

func (c *Rule) WithLocationRFC(location ZoneRFC) *Rule

WithLocationRFC sets the time location using the ZoneRFC value.

Parameters:

  • `location`: A ZoneRFC value representing the time location.

Returns:

  • A pointer to a `Config` struct, which includes the updated configuration.

Example:

rule := NewRule() // This creates a new rule with the default configuration.
rule.WithLocationRFC(DefaultTimezoneVietnam) // This sets the time location to Vietnam.
return rule

func (*Rule) WithTimeFormats

func (c *Rule) WithTimeFormats(timeFormats []string) *Rule

WithTimeFormats sets the time formats.

Parameters:

  • `timeFormats`: A slice of strings representing the time formats.

Returns:

  • A pointer to a `Config` struct, which includes the updated configuration.

Example:

rule := NewRule() // This creates a new rule with the default configuration.
rule.WithTimeFormats([]string{"2006-01-02 15:04:05"}) // This sets the time formats to the default time formats.
return rule

func (*Rule) WithWeekStartDay

func (c *Rule) WithWeekStartDay(weekStartDay time.Weekday) *Rule

WithWeekStartDay sets the week start day.

Parameters:

  • `weekStartDay`: A time.Weekday value representing the week start day.

Returns:

  • A pointer to a `Config` struct, which includes the updated configuration.

Example:

rule := NewRule() // This creates a new rule with the default configuration.
rule.WithWeekStartDay(time.Monday) // This sets the week start day to Monday.
return rule

type TimeFormatRFC

type TimeFormatRFC string
const (
	// Time in format 2006-01-02T15:04:05.999999,
	//	e.g., 2023-08-15T13:45:30.123456
	TimeFormat20060102T150405999999 TimeFormatRFC = "2006-01-02T15:04:05.999999"

	// Time in format 2006-01-02T15:04:05,
	//	e.g., 2023-08-15T13:45:30
	TimeFormat20060102T150405 TimeFormatRFC = "2006-01-02T15:04:05"

	// Time in format 2006-01-02 15:04:05,
	//	e.g., 2023-08-15 13:45:30
	TimeFormat20060102150405 TimeFormatRFC = "2006-01-02 15:04:05"

	// Time in format 02-01-2006 15:04:05,
	//	e.g., 15-08-2023 13:45:30
	TimeFormat02012006150405 TimeFormatRFC = "02-01-2006 15:04:05"

	// Time in format 02/01/2006 15:04:05,
	//	e.g., 15/08/2023 13:45:30
	TimeFormatRFC0102012006150405 TimeFormatRFC = "02/01/2006 15:04:05"

	// Time in format 2006-01-02 15:04:05.999999,
	//	e.g., 2023-08-15 13:45:30.123456
	TimeFormat20060102150405999999 TimeFormatRFC = "2006-01-02 15:04:05.999999"

	// Time in format 2006-01-02 15:04:05.999999999 -07:00,
	//	e.g., 2023-08-15 13:45:30.123456789 -07:00
	TimeFormat20060102150405999999RFC3339 TimeFormatRFC = "2006-01-02 15:04:05.999999999 -07:00"

	// Time in format 2006-01-02,
	//	e.g., 2023-08-15
	TimeFormat20060102 TimeFormatRFC = "2006-01-02"

	// Time in format 02/01/2006,
	//	e.g., 15/08/2023
	TimeFormatRFC0102012006 TimeFormatRFC = "02/01/2006"

	// Time in format 2006-01-02 15:04,
	//	e.g., 2023-08-15 13:45
	TimeFormat200601021504 TimeFormatRFC = "2006-01-02 15:04"

	// Time in format 2006-01-02 15,
	//	e.g., 2023-08-15 13
	TimeFormat2006010215 TimeFormatRFC = "2006-01-02 15"

	// Time in format 2006-01,
	//	e.g., 2023-08
	TimeFormat200601 TimeFormatRFC = "2006-01"

	// Time in format 02-01-2006,
	//	e.g., 15-08-2023
	TimeFormat02012006 TimeFormatRFC = "02-01-2006"

	// Time in format 01-02-2006,
	//	e.g., 08-15-2023
	TimeFormat01022006 TimeFormatRFC = "01-02-2006"

	// Time in format 2006-01-02 15:04:05 -07:00,
	//	e.g., 2023-08-15 13:45:30 -07:00
	TimeFormat20060102150405Z0700 TimeFormatRFC = "2006-01-02 15:04:05 -07:00"

	// Time in format 2006-01-02 15:04:05 -07:00:00,
	//	e.g., 2023-08-15 13:45:30 -07:00:00
	TimeFormat20060102150405Z070000 TimeFormatRFC = "2006-01-02 15:04:05 -07:00:00"

	// Time in format 2006-01-02T15:04:05-07:00,
	//	e.g., 2023-08-15T13:45:30-07:00
	TimeFormat20060102150405Z0700RFC3339 TimeFormatRFC = "2006-01-02T15:04:05-07:00"

	// Time in format 2006-01-02T15:04:05-07:00:00,
	//	e.g., 2023-08-15T13:45:30-07:00:00
	TimeFormat20060102150405Z070000RFC3339 TimeFormatRFC = "2006-01-02T15:04:05-07:00:00"

	// Time in format 2006-01-02 15:04:05 -07,
	//	e.g., 2023-08-15 13:45:30 -07
	TimeFormat20060102150405Z07 TimeFormatRFC = "2006-01-02 15:04:05 -07"

	// Time in format 2006-01-02T15:04:05-07,
	//	e.g., 2023-08-15T13:45:30-07
	TimeFormat20060102150405Z07RFC3339 TimeFormatRFC = "2006-01-02T15:04:05-07"

	// Time in format Mon, 02 Jan 2006 15:04:05 -0700,
	//	e.g., Tue, 15 Aug 2023 13:45:30 -0700
	TimeFormat20060102150405Z0700RFC1123 TimeFormatRFC = "Mon, 02 Jan 2006 15:04:05 -0700"

	// Time in format Mon, 02 Jan 2006 15:04:05 -07:00:00,
	//	e.g., Tue, 15 Aug 2023 13:45:30 -07:00:00
	TimeFormat20060102150405Z070000RFC1123 TimeFormatRFC = "Mon, 02 Jan 2006 15:04:05 -07:00:00"

	// Time in format Mon, 02 Jan 2006 15:04:05 -07,
	//	e.g., Tue, 15 Aug 2023 13:45:30 -07
	TimeFormat20060102150405Z07RFC1123 TimeFormatRFC = "Mon, 02 Jan 2006 15:04:05 -07"

	// Time in format 2006-01-02 15:04:05 UTC-07,
	//	e.g., 2023-08-15 13:45:30 UTC-07
	TimeFormat20060102150405Z07UTC TimeFormatRFC = "2006-01-02 15:04:05 UTC-07"

	// Time in format 2006-01-02 15:04:05 UTC-07:00,
	//	e.g., 2023-08-15 13:45:30 UTC-07:00
	TimeFormat20060102150405Z0700UTC TimeFormatRFC = "2006-01-02 15:04:05 UTC-07:00"

	// Time in format 2006-01-02 15:04:05 UTC-07:00:00,
	//	e.g., 2023-08-15 13:45:30 UTC-07:00:00
	TimeFormat20060102150405Z070000UTC TimeFormatRFC = "2006-01-02 15:04:05 UTC-07:00:00"

	// Time in format 2006-01-02T15:04:05UTC-07,
	//	e.g., 2023-08-15T13:45:30UTC-07
	TimeFormat20060102150405Z07UTCRFC3339 TimeFormatRFC = "2006-01-02T15:04:05UTC-07"

	// Time in format 2006-01-02T15:04:05UTC-07:00,
	//	e.g., 2023-08-15T13:45:30UTC-07:00
	TimeFormat20060102150405Z0700UTCRFC3339 TimeFormatRFC = "2006-01-02T15:04:05UTC-07:00"

	// Time in format 2006-01-02T15:04:05UTC-07:00:00,
	//	e.g., 2023-08-15T13:45:30UTC-07:00:00
	TimeFormat20060102150405Z070000UTCRFC3339 TimeFormatRFC = "2006-01-02T15:04:05UTC-07:00:00"
)

type TimeRFC

type TimeRFC string
const (
	// Time in format 15:04:05,
	//	e.g., 13:45:30
	TimeRFC01T150405 TimeRFC = "15:04:05"

	// Time in format 15.04.05,
	//	e.g., 13.45.30
	TimeRFC02D150405 TimeRFC = "15.04.05"

	// Time in format 15-04-05,
	//	e.g., 13-45-30
	TimeRFC03H150405 TimeRFC = "15-04-05"

	// Time in format 15/04/05,
	//	e.g., 13/45/30
	TimeRFC04M150405 TimeRFC = "15/04/05"

	// Time in format 15 04 05,
	//	e.g., 13 45 30
	TimeRFC05S150405 TimeRFC = "15 04 05"

	// Time in format 150405,
	//	e.g., 134530
	TimeRFC06T150405 TimeRFC = "150405"

	// Time in format 15:04,
	//	e.g., 13:45
	TimeRFC07D150405 TimeRFC = "15:04"

	// Time in format 15.04,
	//	e.g., 13.45
	TimeRFC08H150405 TimeRFC = "15.04"

	// Time in format 15-04,
	//	e.g., 13-45
	TimeRFC09M150405 TimeRFC = "15-04"

	// Time in format 15/04,
	//	e.g., 13/45
	TimeRFC10S150405 TimeRFC = "15/04"

	// Time in format 1504,
	//	e.g., 1345
	TimeRFC11T150405 TimeRFC = "1504"
)

type Timex

type Timex struct {
	time.Time
	*Rule
}

func New

func New(v time.Time) *Timex

New creates a new Timex object for the provided time value `v`.

The function calls the `With()` function, which wraps the given time in a `Timex` struct and applies the default configuration (or a custom one if set). Essentially, this function is a shorthand for creating a `Timex` object.

Parameters:

  • `v`: A time.Time value representing the time to be wrapped inside the Timex struct.

Returns:

  • A pointer to a `Timex` struct, which includes the provided time and the applicable configuration.

Example:

t := time.Now()
timex := New(t) // This creates a new Timex object for the current time.

func With

func With(v time.Time) *Timex

With wraps the provided time value `v` into a Timex object, applying the default configuration.

The function first checks if the global `DefaultConfig` is set. If it is not, it initializes a new `Config` with default values for `WeekStartDay` and `TimeFormats`. The configuration and time are then used to create a `Timex` object.

Parameters:

  • `v`: A time.Time value representing the time to be wrapped inside the Timex struct.

Returns:

  • A pointer to a `Timex` struct, which includes the provided time and either the default or a custom configuration.

Example:

t := time.Now()
timex := With(t) // This wraps the current time into a Timex object with the default configuration.

func (*Timex) BeginningOfDay

func (t *Timex) BeginningOfDay() time.Time

BeginningOfDay returns a new time.Time value representing the start of the day for the given Timex instance.

The function retrieves the year, month, and day from the underlying time.Time of the Timex struct using the `Date()` method. It then constructs a new time.Time value with the same year, month, and day but sets the hour, minute, second, and nanosecond to zero. This effectively resets the time to midnight (00:00:00) of the same date, providing the start of the day.

Returns:

  • A `time.Time` value representing the start of the day for the current Timex instance.

Example:

t := Timex{Time: time.Now()}
startOfDay := t.BeginningOfDay() // This will return the current date at 00:00:00 (midnight).

func (*Timex) BeginningOfHalf

func (t *Timex) BeginningOfHalf() time.Time

BeginningOfHalf returns a new time.Time value representing the start of the half-year for the given Timex instance.

The function first calculates the start of the current month using `BeginningOfMonth()`. It then determines how far the current month is into the half-year by calculating the offset (based on a 6-month system). The offset is subtracted from the current month to return a time value corresponding to the start of the half-year (e.g., if the current month is July, it will return the start of July; if it's October, it will return the start of July).

Returns:

  • A `time.Time` value representing the start of the half-year for the current Timex instance.

Example:

t := Timex{Time: time.Now()}
startOfHalf := t.BeginningOfHalf() // This will return the date and time at the start of the current half-year.

func (*Timex) BeginningOfHour

func (t *Timex) BeginningOfHour() time.Time

BeginningOfHour returns a new time.Time value representing the start of the hour for the given Timex instance.

The function retrieves the year, month, and day from the underlying time.Time of the Timex struct using the `Date()` method. It then constructs a new time.Time value with the same year, month, and day but sets the hour to the current hour and resets the minutes, seconds, and nanoseconds to zero. This effectively provides the time corresponding to the beginning of the current hour.

Returns:

  • A `time.Time` value representing the start of the hour for the current Timex instance.

Example:

t := Timex{Time: time.Now()}
startOfHour := t.BeginningOfHour() // This will return the current time truncated to the start of the hour.

func (*Timex) BeginningOfMinute

func (t *Timex) BeginningOfMinute() time.Time

BeginningOfMinute returns a new time.Time value representing the start of the minute for the given Timex instance.

The function uses the `Truncate()` method on the underlying time.Time of the Timex struct, truncating the time to the nearest minute. This effectively resets the seconds and nanoseconds to zero, providing the time corresponding to the beginning of the current minute.

Returns:

  • A `time.Time` value representing the start of the minute for the current Timex instance.

Example:

t := Timex{Time: time.Now()}
startOfMinute := t.BeginningOfMinute() // This will return the current time truncated to the start of the minute.

func (*Timex) BeginningOfMonth

func (t *Timex) BeginningOfMonth() time.Time

BeginningOfMonth returns a new time.Time value representing the start of the month for the given Timex instance.

The function retrieves the year and month from the underlying time.Time of the Timex struct using the `Date()` method. It then constructs a new time.Time value with the same year and month, but sets the day to the first of the month and resets the hour, minute, second, and nanosecond to zero, providing the start of the month.

Returns:

  • A `time.Time` value representing the start of the month for the current Timex instance.

Example:

t := Timex{Time: time.Now()}
startOfMonth := t.BeginningOfMonth() // This will return the date and time at the start of the current month.

func (*Timex) BeginningOfQuarter

func (t *Timex) BeginningOfQuarter() time.Time

BeginningOfQuarter returns a new time.Time value representing the start of the quarter for the given Timex instance.

The function first calculates the start of the current month using `BeginningOfMonth()`. It then determines how far the current month is into the quarter by calculating the offset (based on a 3-month quarter system). The offset is subtracted from the current month to return a time value corresponding to the start of the quarter (e.g., if the current month is April, it will return the start of April; if it's June, it will return the start of April).

Returns:

  • A `time.Time` value representing the start of the quarter for the current Timex instance.

Example:

t := Timex{Time: time.Now()}
startOfQuarter := t.BeginningOfQuarter() // This will return the date and time at the start of the current quarter.

func (*Timex) BeginningOfWeek

func (t *Timex) BeginningOfWeek() time.Time

BeginningOfWeek returns a new time.Time value representing the start of the week for the

given Timex instance, based on the configured `WeekStartDay`.

The function first calculates the beginning of the current day using `BeginningOfDay()`. Then, it determines the current weekday and calculates how many days to subtract in order to reach the start of the week, based on the configured start day (`WeekStartDay`). If `WeekStartDay` is set to a day other than Sunday, the function adjusts the number of days to move back accordingly.

Returns:

  • A `time.Time` value representing the start of the week for the current Timex instance.

Example:

t := Timex{Time: time.Now(), Config: &Config{WeekStartDay: time.Monday}}
startOfWeek := t.BeginningOfWeek() // This will return the date and time at the start of the current week.

Note:

If `WeekStartDay` is not set (defaults to Sunday), the function will return the preceding Sunday.

func (*Timex) BeginningOfYear

func (t *Timex) BeginningOfYear() time.Time

BeginningOfYear returns a new time.Time value representing the start of the year for the given Timex instance.

The function retrieves the year from the underlying time.Time of the Timex struct using the `Date()` method. It then constructs a new time.Time value with the same year but sets the month to January, and the day, hour, minute, second, and nanosecond to zero. This effectively resets the time to midnight (00:00:00) on January 1st of the current year.

Returns:

  • A `time.Time` value representing the start of the year for the current Timex instance.

Example:

t := Timex{Time: time.Now()}
startOfYear := t.BeginningOfYear() // This will return January 1st of the current year at 00:00:00.

func (*Timex) Between

func (t *Timex) Between(begin, end string) bool

Between checks if the current Timex instance's time falls within the specified time range, defined by the provided `begin` and `end` date strings. The function parses the strings into time.Time values and determines if the current time is after the `begin` time and before the `end` time.

Parameters:

  • `begin`: A string representing the start of the time range; it will be parsed into a time.Time value.
  • `end`: A string representing the end of the time range; it will also be parsed into a time.Time value.

Returns:

  • A boolean value indicating whether the current time is within the specified range (exclusive). It returns true if the current time is after `begin` and before `end`; otherwise, it returns false.

Example:

t := Timex{Time: time.Now()}
isInRange := t.Between("2023-10-01", "2023-10-31") // Checks if the current time is in October 2023.

Note:

  • If the parsing of `begin` or `end` fails, the function will panic due to the usage of `MustParse`.

func (*Timex) DefaultFormatRFC

func (t *Timex) DefaultFormatRFC() string

DefaultFormatRFC formats the time using a default layout that includes the date and time with nanosecond precision.

Returns:

  • A string representing the formatted time in the default RFC format.

func (*Timex) DurationInDays

func (t *Timex) DurationInDays(other time.Time) int

DurationInDays returns the duration between the current time and another time in days.

Parameters:

  • `other`: The other time to calculate the duration from.

Returns:

  • An integer representing the duration in days.

Example:

t := Timex{Time: time.Now()}
formatted := t.DurationInDays(time.Now().AddDate(0, 0, 1)) // Returns 1

func (*Timex) DurationInMonths

func (t *Timex) DurationInMonths(other time.Time) int

DurationInMonths returns the duration between the current time and another time in months.

Parameters:

  • `other`: The other time to calculate the duration from.

Returns:

  • An integer representing the duration in months.

Example:

t := Timex{Time: time.Now()}
formatted := t.DurationInMonths(time.Now().AddDate(0, 1, 0)) // Returns 1

func (*Timex) DurationInWeeks

func (t *Timex) DurationInWeeks(other time.Time) int

DurationInWeeks returns the duration between the current time and another time in weeks.

Parameters:

  • `other`: The other time to calculate the duration from.

Returns:

  • An integer representing the duration in weeks.

Example:

t := Timex{Time: time.Now()}
formatted := t.DurationInWeeks(time.Now().AddDate(0, 0, 7)) // Returns 1

func (*Timex) DurationInYears

func (t *Timex) DurationInYears(other time.Time) int

DurationInYears returns the duration between the current time and another time in years.

Parameters:

  • `other`: The other time to calculate the duration from.

Returns:

  • An integer representing the duration in years.

Example:

t := Timex{Time: time.Now()}
formatted := t.DurationInYears(time.Now().AddDate(1, 0, 0)) // Returns 1

func (*Timex) EndOfDay

func (t *Timex) EndOfDay() time.Time

EndOfDay returns a new time.Time value representing the end of the current day for the given Timex instance.

The function retrieves the year, month, and day from the underlying time.Time of the Timex struct using the `Date()` method. It then constructs a new time.Time value with the same year, month, and day but sets the time to 23:59:59.999999999, which is the last nanosecond of the day.

Returns:

  • A `time.Time` value representing the end of the current day for the Timex instance.

Example:

t := Timex{Time: time.Now()}
endOfDay := t.EndOfDay() // This will return the date and time at the end of the current day (23:59:59.999999999).

func (*Timex) EndOfHalf

func (t *Timex) EndOfHalf() time.Time

EndOfHalf returns a new time.Time value representing the end of the current half-year for the given Timex instance.

The function first calculates the start of the half-year using `BeginningOfHalf()`, then adds six months to reach the beginning of the next half-year, and subtracts one nanosecond to obtain the last nanosecond of the current half-year.

Returns:

  • A `time.Time` value representing the end of the current half-year for the Timex instance.

Example:

t := Timex{Time: time.Now()}
endOfHalf := t.EndOfHalf() // This will return the date and time at the end of the current half-year (e.g., 23:59:59.999999999 on June 30th or December 31st).

func (*Timex) EndOfHour

func (t *Timex) EndOfHour() time.Time

EndOfHour returns a new time.Time value representing the end of the current hour for the given Timex instance.

The function first calculates the start of the hour using `BeginningOfHour()`, then adds one hour and subtracts a nanosecond to reach the last nanosecond of the current hour.

Returns:

  • A `time.Time` value representing the end of the current hour for the Timex instance.

Example:

t := Timex{Time: time.Now()}
endOfHour := t.EndOfHour() // This will return the time at the end of the current hour (59:59.999999999).

func (*Timex) EndOfMinute

func (t *Timex) EndOfMinute() time.Time

EndOfMinute returns a new time.Time value representing the end of the current minute for the given Timex instance.

The function first calculates the start of the minute using `BeginningOfMinute()`, then adds one minute and subtracts a nanosecond. This adjustment effectively gives the time at the last nanosecond of the current minute.

Returns:

  • A `time.Time` value representing the end of the current minute for the Timex instance.

Example:

t := Timex{Time: time.Now()}
endOfMinute := t.EndOfMinute() // This will return the time at the end of the current minute (59.999999999 nanoseconds).

func (*Timex) EndOfMonth

func (t *Timex) EndOfMonth() time.Time

EndOfMonth returns a new time.Time value representing the end of the current month for the given Timex instance.

The function first calculates the start of the month using `BeginningOfMonth()`, then adds one month to reach the beginning of the next month, and subtracts one nanosecond to obtain the last nanosecond of the current month.

Returns:

  • A `time.Time` value representing the end of the current month for the Timex instance.

Example:

t := Timex{Time: time.Now()}
endOfMonth := t.EndOfMonth() // This will return the date and time at the end of the current month (e.g., 23:59:59.999999999 on the last day).

func (*Timex) EndOfQuarter

func (t *Timex) EndOfQuarter() time.Time

EndOfQuarter returns a new time.Time value representing the end of the current quarter for the given Timex instance.

The function first calculates the start of the quarter using `BeginningOfQuarter()`, then adds three months to reach the beginning of the next quarter, and subtracts one nanosecond to obtain the last nanosecond of the current quarter.

Returns:

  • A `time.Time` value representing the end of the current quarter for the Timex instance.

Example:

t := Timex{Time: time.Now()}
endOfQuarter := t.EndOfQuarter() // This will return the date and time at the end of the current quarter (e.g., 23:59:59.999999999 on the last day of the quarter).

func (*Timex) EndOfSunday

func (t *Timex) EndOfSunday() time.Time

EndOfSunday returns a new time.Time value representing the end of the most recent or upcoming Sunday for the given Timex instance.

The function first calculates the start of the most recent or upcoming Sunday using `Sunday()`, then constructs a new Timex instance with that date and time. Finally, it calls `EndOfDay()` on this instance to retrieve the time at the last nanosecond of the Sunday.

Returns:

  • A `time.Time` value representing the end of the most recent or upcoming Sunday for the Timex instance.

Example:

t := Timex{Time: time.Now()}
endOfSunday := t.EndOfSunday() // Returns the date and time at the end of the most recent or upcoming Sunday (23:59:59.999999999).

func (*Timex) EndOfWeek

func (t *Timex) EndOfWeek() time.Time

EndOfWeek returns a new time.Time value representing the end of the current week for the given Timex instance, based on the configured `WeekStartDay`.

The function first calculates the start of the current week using `BeginningOfWeek()`, then adds 7 days to reach the start of the next week, and subtracts one nanosecond to get the last nanosecond of the current week.

Returns:

  • A `time.Time` value representing the end of the current week for the Timex instance.

Example:

t := Timex{Time: time.Now(), Config: &Config{WeekStartDay: time.Monday}}
endOfWeek := t.EndOfWeek() // This will return the date and time at the end of the current week.

Note:

If `WeekStartDay` is not set (defaults to Sunday), the function will return the preceding Saturday at 23:59:59.999999999.

func (*Timex) EndOfYear

func (t *Timex) EndOfYear() time.Time

EndOfYear returns a new time.Time value representing the end of the current year for the given Timex instance.

The function first calculates the start of the year using `BeginningOfYear()`, then adds one year to reach the beginning of the next year, and subtracts one nanosecond to obtain the last nanosecond of the current year.

Returns:

  • A `time.Time` value representing the end of the current year for the Timex instance.

Example:

t := Timex{Time: time.Now()}
endOfYear := t.EndOfYear() // This will return the date and time at the end of the current year (e.g., 23:59:59.999999999 on December 31st).

func (*Timex) FormatRFC

func (t *Timex) FormatRFC(layout TimeFormatRFC) string

FormatRFC formats the time using the provided layout.

Parameters:

  • `layout`: A TimeFormatRFC value representing the layout to use for formatting.

Returns:

  • A string representing the formatted time.

Example:

t := Timex{Time: time.Now()}
formatted := t.FormatRFC(TimeFormat20060102T150405) // Returns the formatted time in the format "2023-08-15 13:45:30".

func (*Timex) FormatRFCshort

func (t *Timex) FormatRFCshort(layout TimeRFC) string

FormatRFCshort formats the time using the provided layout.

Parameters:

  • `layout`: A TimeRFC value representing the layout to use for formatting.

Returns:

  • A string representing the formatted time.

Example:

t := Timex{Time: time.Now()}
formatted := t.FormatRFCshort(TimeRFC01T150405) // Returns the formatted time in the format "13:45:30".

func (*Timex) Friday

func (t *Timex) Friday(s ...string) time.Time

Friday returns a new time.Time value representing the most recent Friday at the start of the week based on the provided date string(s) or the current date if no date strings are provided.

If a date string is provided, it parses the date using the Timex `Parse` method. If no string is provided, the function defaults to the start of the current day. It then determines the weekday of the parsed date. If the weekday is Sunday (represented by 0), it adjusts to be the seventh day for calculation purposes. The function finally subtracts the necessary days to reach the last Friday.

Parameters:

  • s ...string: Optional date string(s) to parse; if none are provided, it defaults to today.

Returns:

  • A `time.Time` value representing the date and time at the start of the last Friday.

Example:

t := Timex{Time: time.Now()}
lastFriday := t.Friday() // Returns the start of the most recent Friday.

Note:

If parsing fails, the function will panic with an error.

func (*Timex) FridaySafe

func (t *Timex) FridaySafe(s ...string) (time.Time, error)

FridaySafe returns a new time.Time value representing the most recent Friday at the start of the week based on the provided date string(s) or the current date if no date strings are provided. Unlike Friday(), this method returns an error instead of panicking on parse failures.

Parameters:

  • s ...string: Optional date string(s) to parse; if none are provided, it defaults to today.

Returns:

  • A `time.Time` value representing the date and time at the start of the last Friday.
  • An error if parsing fails.

func (*Timex) IsAfter

func (t *Timex) IsAfter(other time.Time) bool

IsAfter checks if the current time is after the specified time.

Parameters:

  • `other`: The other time to compare against.

Returns:

  • A boolean value indicating whether the current time is after the specified time.

Example:

t := Timex{Time: time.Now()}
isAfter := t.IsAfter(time.Now().AddDate(0, 0, 1)) // Returns true if the current time is after the specified time

func (*Timex) IsBefore

func (t *Timex) IsBefore(other time.Time) bool

IsBefore checks if the current time is before the specified time.

Parameters:

  • `other`: The other time to compare against.

Returns:

  • A boolean value indicating whether the current time is before the specified time.

Example:

t := Timex{Time: time.Now()}
isBefore := t.IsBefore(time.Now().AddDate(0, 0, 1)) // Returns true if the current time is before the specified time

func (*Timex) IsBetween

func (t *Timex) IsBetween(start, end time.Time) bool

IsBetween checks if the current time is between the specified start and end times (inclusive).

Parameters:

  • `start`: The start time of the range.
  • `end`: The end time of the range.

Returns:

  • A boolean value indicating whether the current time is between the specified start and end times.

Example:

t := Timex{Time: time.Now()}
isBetween := t.IsBetween(time.Now().AddDate(0, 0, 1), time.Now().AddDate(0, 0, 2)) // Returns true if the current time is between the specified start and end times

func (*Timex) IsFuture

func (t *Timex) IsFuture() bool

IsFuture checks if the current time is in the future.

Returns:

  • A boolean value indicating whether the current time is in the future.

Example:

t := Timex{Time: time.Now()}
isFuture := t.IsFuture() // Returns true if the current time is in the future

func (*Timex) IsPast

func (t *Timex) IsPast() bool

IsPast checks if the current time is in the past.

Returns:

  • A boolean value indicating whether the current time is in the past.

Example:

t := Timex{Time: time.Now()}
isPast := t.IsPast() // Returns true if the current time is in the past

func (*Timex) IsSameDay

func (t *Timex) IsSameDay(other time.Time) bool

IsSameDay checks if the current time is on the same day as the specified time.

Parameters:

  • `other`: The other time to compare against.

Returns:

  • A boolean value indicating whether the current time is on the same day as the specified time.

Example:

t := Timex{Time: time.Now()}
isSameDay := t.IsSameDay(time.Now().AddDate(0, 0, 1)) // Returns true if the current time is on the same day as the specified time

func (*Timex) IsSameMonth

func (t *Timex) IsSameMonth(other time.Time) bool

IsSameMonth checks if the current time is on the same month as the specified time.

Parameters:

  • `other`: The other time to compare against.

Returns:

  • A boolean value indicating whether the current time is on the same month as the specified time.

Example:

t := Timex{Time: time.Now()}
isSameMonth := t.IsSameMonth(time.Now().AddDate(0, 1, 0)) // Returns true if the current time is on the same month as the specified time

func (*Timex) IsSameYear

func (t *Timex) IsSameYear(other time.Time) bool

IsSameYear checks if the current time is on the same year as the specified time.

Parameters:

  • `other`: The other time to compare against.

Returns:

  • A boolean value indicating whether the current time is on the same year as the specified time.

Example:

t := Timex{Time: time.Now()}
isSameYear := t.IsSameYear(time.Now().AddDate(1, 0, 0)) // Returns true if the current time is on the same year as the specified time

func (*Timex) IsToday

func (t *Timex) IsToday() bool

IsToday checks if the current time is today.

Returns:

  • A boolean value indicating whether the current time is today.

Example:

t := Timex{Time: time.Now()}
isToday := t.IsToday() // Returns true if the current time is today

func (*Timex) IsTomorrow

func (t *Timex) IsTomorrow() bool

IsTomorrow checks if the current time is tomorrow.

Returns:

  • A boolean value indicating whether the current time is tomorrow.

Example:

t := Timex{Time: time.Now()}
isTomorrow := t.IsTomorrow() // Returns true if the current time is tomorrow

func (*Timex) IsWeekday

func (t *Timex) IsWeekday() bool

IsWeekday checks if the current time is a weekday (Monday to Friday).

Returns:

  • A boolean value indicating whether the current time is a weekday.

Example:

t := Timex{Time: time.Now()}
isWeekday := t.IsWeekday() // Returns true if the current time is a weekday

func (*Timex) IsWeekend

func (t *Timex) IsWeekend() bool

IsWeekend checks if the current time is a weekend (Saturday or Sunday).

Returns:

  • A boolean value indicating whether the current time is a weekend.

Example:

t := Timex{Time: time.Now()}
isWeekend := t.IsWeekend() // Returns true if the current time is a weekend

func (*Timex) IsYesterday

func (t *Timex) IsYesterday() bool

IsYesterday checks if the current time is yesterday.

Returns:

  • A boolean value indicating whether the current time is yesterday.

Example:

t := Timex{Time: time.Now()}
isYesterday := t.IsYesterday() // Returns true if the current time is yesterday

func (*Timex) Monday

func (t *Timex) Monday(s ...string) time.Time

Monday returns a new time.Time value representing the most recent Monday at the start of the week based on the provided date string(s) or the current date if no date strings are provided.

If a date string is provided, it parses the date using the Timex `Parse` method. If no string is provided, the function defaults to the start of the current day. It then determines the weekday of the parsed date. If the weekday is Sunday (represented by 0), it adjusts to be the seventh day for calculation purposes. The function finally subtracts the necessary days to reach the last Monday.

Parameters:

  • s ...string: Optional date string(s) to parse; if none are provided, it defaults to today.

Returns:

  • A `time.Time` value representing the date and time at the start of the last Monday.

Example:

t := Timex{Time: time.Now()}
lastMonday := t.Monday() // Returns the start of the most recent Monday.

Note:

If parsing fails, the function will panic with an error.

func (*Timex) MondaySafe

func (t *Timex) MondaySafe(s ...string) (time.Time, error)

MondaySafe returns a new time.Time value representing the most recent Monday at the start of the week based on the provided date string(s) or the current date if no date strings are provided. Unlike Monday(), this method returns an error instead of panicking on parse failures.

Parameters:

  • s ...string: Optional date string(s) to parse; if none are provided, it defaults to today.

Returns:

  • A `time.Time` value representing the date and time at the start of the last Monday.
  • An error if parsing fails.

func (*Timex) MustParse

func (t *Timex) MustParse(s ...string) (v time.Time)

MustParse interprets the provided date string(s) and converts them into a time.Time value, but it panics if parsing fails. This is useful for scenarios where a valid time is essential, and failure to parse should result in a program error.

The function calls the `Parse` method, which attempts to interpret each date string according to the configured formats, adjusting for the current time and location as necessary. If the parsing succeeds, the resulting time.Time value is returned; if it fails, a panic is triggered with the associated error message.

Parameters:

  • `s ...string`: One or more date strings to be parsed. The function will try to parse each string in the order provided and will panic if none can be successfully parsed.

Returns:

  • `v`: A `time.Time` value representing the parsed date and time, guaranteed to be valid as the function will panic on failure.

Example:

t := Timex{Time: time.Now()}
parsedTime := t.MustParse("2023-10-25 15:04") // Attempts to parse the given date strings.
// If parsing fails, it will panic.

Note:

  • This function is intended for use cases where the caller must have a valid time returned, and any parsing errors should be treated as unrecoverable conditions.

func (*Timex) Parse

func (t *Timex) Parse(s ...string) (value time.Time, err error)

Parse interprets the provided date string(s) and converts them into a time.Time value. It attempts to parse each string according to the configured formats, adjusting for the current time and location as necessary.

The function checks each string for time information and adjusts the date components accordingly. If a date component is missing (e.g., day, month, year) in the parsed string, it will replace it with the corresponding component from the current time. If the input string includes only time, it sets the day and month to those of the current date. The function handles various cases for the input strings and parses them into a valid time.Time value.

Parameters:

  • `s ...string`: One or more date strings to be parsed. The function will try to parse each string in the order provided and will return the first successful parsed time.

Returns:

  • `value`: A `time.Time` value representing the parsed date and time.
  • `err`: An error value indicating any issues that occurred during parsing; if parsing is successful, this will be nil.

Example:

t := Timex{Time: time.Now()}
parsedTime, err := t.Parse("2023-10-25 15:04", "15:04") // Attempts to parse the given date strings.
if err != nil {
	// Handle error
}

Note: - The function modifies the parsed date based on the current time when certain components are missing. - It will return the most recent successful parsed value or the zero value of time.Time if none succeed.

func (*Timex) Quarter

func (t *Timex) Quarter() uint

Quarter returns the current quarter of the year for the given Timex instance, where the year is divided into four quarters: Q1 (January-March), Q2 (April-June), Q3 (July-September), and Q4 (October-December).

The function calculates the quarter by taking the current month (retrieved using the `Month()` method), subtracting one (to account for zero-based indexing), dividing by 3, and then adding 1 to get the quarter number. This results in a value between 1 and 4, representing the quarter of the year.

Returns:

  • A `uint` value representing the current quarter (1 to 4) for the Timex instance.

Example:

t := Timex{Time: time.Now()}
quarter := t.Quarter() // Returns the current quarter number (1, 2, 3, or 4).

func (*Timex) Saturday

func (t *Timex) Saturday(s ...string) time.Time

Saturday returns a new time.Time value representing the most recent Saturday at the start of the week based on the provided date string(s) or the current date if no date strings are provided.

If a date string is provided, it parses the date using the Timex `Parse` method. If no string is provided, the function defaults to the start of the current day. It then determines the weekday of the parsed date. If the weekday is Sunday (represented by 0), it adjusts to be the seventh day for calculation purposes. The function finally subtracts the necessary days to reach the last Saturday.

Parameters:

  • s ...string: Optional date string(s) to parse; if none are provided, it defaults to today.

Returns:

  • A `time.Time` value representing the date and time at the start of the last Saturday.

Example:

t := Timex{Time: time.Now()}
lastSaturday := t.Saturday() // Returns the start of the most recent Saturday.

Note:

If parsing fails, the function will panic with an error.

func (*Timex) SaturdaySafe

func (t *Timex) SaturdaySafe(s ...string) (time.Time, error)

SaturdaySafe returns a new time.Time value representing the most recent Saturday at the start of the week based on the provided date string(s) or the current date if no date strings are provided. Unlike Saturday(), this method returns an error instead of panicking on parse failures.

Parameters:

  • s ...string: Optional date string(s) to parse; if none are provided, it defaults to today.

Returns:

  • A `time.Time` value representing the date and time at the start of the last Saturday.
  • An error if parsing fails.

func (*Timex) Sunday

func (t *Timex) Sunday(s ...string) time.Time

Sunday returns a new time.Time value representing the most recent or upcoming Sunday based on the provided date string(s) or the current date if no date strings are provided.

If a date string is provided, it parses the date using the Timex `Parse` method. If no string is provided, the function defaults to the start of the current day. It then determines the weekday of the parsed date. If the weekday is Sunday (represented by 0), it adjusts to be the seventh day for calculation purposes. The function finally adds the necessary days to reach the next Sunday.

Parameters:

  • s ...string: Optional date string(s) to parse; if none are provided, it defaults to today.

Returns:

  • A `time.Time` value representing the date and time at the start of the most recent or upcoming Sunday.

Example:

t := Timex{Time: time.Now()}
lastSunday := t.Sunday() // Returns the date and time at the start of the most recent or upcoming Sunday.

Note:

If parsing fails, the function will panic with an error.

func (*Timex) SundaySafe

func (t *Timex) SundaySafe(s ...string) (time.Time, error)

SundaySafe returns a new time.Time value representing the upcoming Sunday based on the provided date string(s) or the current date if no date strings are provided. Unlike Sunday(), this method returns an error instead of panicking on parse failures.

Note: This method uses the same algorithm as the other weekday methods but with an offset calculation that always returns a future Sunday (or today if it's already Sunday at midnight). If the current day is Sunday, it returns the next Sunday (7 days later).

Parameters:

  • s ...string: Optional date string(s) to parse; if none are provided, it defaults to today.

Returns:

  • A `time.Time` value representing the date and time at the start of the upcoming Sunday.
  • An error if parsing fails.

func (*Timex) Thursday

func (t *Timex) Thursday(s ...string) time.Time

Thursday returns a new time.Time value representing the most recent Thursday at the start of the week based on the provided date string(s) or the current date if no date strings are provided.

If a date string is provided, it parses the date using the Timex `Parse` method. If no string is provided, the function defaults to the start of the current day. It then determines the weekday of the parsed date. If the weekday is Sunday (represented by 0), it adjusts to be the seventh day for calculation purposes. The function finally subtracts the necessary days to reach the last Thursday.

Parameters:

  • s ...string: Optional date string(s) to parse; if none are provided, it defaults to today.

Returns:

  • A `time.Time` value representing the date and time at the start of the last Thursday.

Example:

t := Timex{Time: time.Now()}
lastThursday := t.Thursday() // Returns the start of the most recent Thursday.

Note:

If parsing fails, the function will panic with an error.

func (*Timex) ThursdaySafe

func (t *Timex) ThursdaySafe(s ...string) (time.Time, error)

ThursdaySafe returns a new time.Time value representing the most recent Thursday at the start of the week based on the provided date string(s) or the current date if no date strings are provided. Unlike Thursday(), this method returns an error instead of panicking on parse failures.

Parameters:

  • s ...string: Optional date string(s) to parse; if none are provided, it defaults to today.

Returns:

  • A `time.Time` value representing the date and time at the start of the last Thursday.
  • An error if parsing fails.

func (*Timex) TimeAgo

func (t *Timex) TimeAgo() string

TimeAgo returns a human-readable string representing the time difference between the current time and the specified time. It uses the local time zone for calculations and returns a relative time string (e.g., "just now", "5 minutes ago", "2 weeks ago").

Parameters:

  • `t`: A pointer to the Timex instance containing the time to compare.

Returns:

  • A string representing the relative time difference.

Example:

t := Timex{Time: time.Now().Add(-5 * time.Minute)}
fmt.Println(t.TimeAgo()) // Output: "5 minutes ago"

func (*Timex) TimeUntil

func (t *Timex) TimeUntil() string

TimeUntil returns a human-readable string representing the time difference between the current time and the specified time. It uses the local time zone for calculations and returns a relative time string (e.g., "in a few seconds", "in 5 minutes", "in 2 weeks").

Parameters:

  • `t`: A pointer to the Timex instance containing the time to compare.

Returns:

  • A string representing the relative time difference.

Example:

t := Timex{Time: time.Now().Add(5 * time.Minute)}
fmt.Println(t.TimeUntil()) // Output: "in 5 minutes"

func (*Timex) Tuesday

func (t *Timex) Tuesday(s ...string) time.Time

Tuesday returns a new time.Time value representing the most recent Tuesday at the start of the week based on the provided date string(s) or the current date if no date strings are provided.

If a date string is provided, it parses the date using the Timex `Parse` method. If no string is provided, the function defaults to the start of the current day. It then determines the weekday of the parsed date. If the weekday is Sunday (represented by 0), it adjusts to be the seventh day for calculation purposes. The function finally subtracts the necessary days to reach the last Tuesday.

Parameters:

  • s ...string: Optional date string(s) to parse; if none are provided, it defaults to today.

Returns:

  • A `time.Time` value representing the date and time at the start of the last Tuesday.

Example:

t := Timex{Time: time.Now()}
lastTuesday := t.Tuesday() // Returns the start of the most recent Tuesday.

Note:

If parsing fails, the function will panic with an error.

func (*Timex) TuesdaySafe

func (t *Timex) TuesdaySafe(s ...string) (time.Time, error)

TuesdaySafe returns a new time.Time value representing the most recent Tuesday at the start of the week based on the provided date string(s) or the current date if no date strings are provided. Unlike Tuesday(), this method returns an error instead of panicking on parse failures.

Parameters:

  • s ...string: Optional date string(s) to parse; if none are provided, it defaults to today.

Returns:

  • A `time.Time` value representing the date and time at the start of the last Tuesday.
  • An error if parsing fails.

func (*Timex) Wednesday

func (t *Timex) Wednesday(s ...string) time.Time

Wednesday returns a new time.Time value representing the most recent Wednesday at the start of the week based on the provided date string(s) or the current date if no date strings are provided.

If a date string is provided, it parses the date using the Timex `Parse` method. If no string is provided, the function defaults to the start of the current day. It then determines the weekday of the parsed date. If the weekday is Sunday (represented by 0), it adjusts to be the seventh day for calculation purposes. The function finally subtracts the necessary days to reach the last Wednesday.

Parameters:

  • s ...string: Optional date string(s) to parse; if none are provided, it defaults to today.

Returns:

  • A `time.Time` value representing the date and time at the start of the last Wednesday.

Example:

t := Timex{Time: time.Now()}
lastWednesday := t.Wednesday() // Returns the start of the most recent Wednesday.

Note:

If parsing fails, the function will panic with an error.

func (*Timex) WednesdaySafe

func (t *Timex) WednesdaySafe(s ...string) (time.Time, error)

WednesdaySafe returns a new time.Time value representing the most recent Wednesday at the start of the week based on the provided date string(s) or the current date if no date strings are provided. Unlike Wednesday(), this method returns an error instead of panicking on parse failures.

Parameters:

  • s ...string: Optional date string(s) to parse; if none are provided, it defaults to today.

Returns:

  • A `time.Time` value representing the date and time at the start of the last Wednesday.
  • An error if parsing fails.

type ZoneRFC

type ZoneRFC string
const (
	// DefaultTimezoneVietnam is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Vietnam, which is "Asia/Ho_Chi_Minh".
	DefaultTimezoneVietnam ZoneRFC = "Asia/Ho_Chi_Minh"

	// DefaultTimezoneNewYork is a constant that holds the IANA Time Zone identifier
	// for the default timezone in New York, USA, which is "America/New_York".
	DefaultTimezoneNewYork ZoneRFC = "America/New_York"

	// DefaultTimezoneLondon is a constant that holds the IANA Time Zone identifier
	// for the default timezone in London, United Kingdom, which is "Europe/London".
	DefaultTimezoneLondon ZoneRFC = "Europe/London"

	// DefaultTimezoneTokyo is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Tokyo, Japan, which is "Asia/Tokyo".
	DefaultTimezoneTokyo ZoneRFC = "Asia/Tokyo"

	// DefaultTimezoneSydney is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Sydney, Australia, which is "Australia/Sydney".
	DefaultTimezoneSydney ZoneRFC = "Australia/Sydney"

	// DefaultTimezoneParis is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Paris, France, which is "Europe/Paris".
	DefaultTimezoneParis ZoneRFC = "Europe/Paris"

	// DefaultTimezoneMoscow is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Moscow, Russia, which is "Europe/Moscow".
	DefaultTimezoneMoscow ZoneRFC = "Europe/Moscow"

	// DefaultTimezoneLosAngeles is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Los Angeles, USA, which is "America/Los_Angeles".
	DefaultTimezoneLosAngeles ZoneRFC = "America/Los_Angeles"

	// DefaultTimezoneManila is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Manila, Philippines, which is "Asia/Manila".
	DefaultTimezoneManila ZoneRFC = "Asia/Manila"

	// DefaultTimezoneKualaLumpur is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Kuala Lumpur, Malaysia, which is "Asia/Kuala_Lumpur".
	DefaultTimezoneKualaLumpur ZoneRFC = "Asia/Kuala_Lumpur"

	// DefaultTimezoneJakarta is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Jakarta, Indonesia, which is "Asia/Jakarta".
	DefaultTimezoneJakarta ZoneRFC = "Asia/Jakarta"

	// DefaultTimezoneYangon is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Yangon, Myanmar, which is "Asia/Yangon".
	DefaultTimezoneYangon ZoneRFC = "Asia/Yangon"

	// DefaultTimezoneAuckland is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Auckland, New Zealand, which is "Pacific/Auckland".
	DefaultTimezoneAuckland ZoneRFC = "Pacific/Auckland"

	// DefaultTimezoneBangkok is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Bangkok, Thailand, which is "Asia/Bangkok".
	DefaultTimezoneBangkok ZoneRFC = "Asia/Bangkok"

	// DefaultTimezoneDelhi is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Delhi, India, which is "Asia/Kolkata".
	DefaultTimezoneDelhi ZoneRFC = "Asia/Kolkata"

	// DefaultTimezoneDubai is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Dubai, United Arab Emirates, which is "Asia/Dubai".
	DefaultTimezoneDubai ZoneRFC = "Asia/Dubai"

	// DefaultTimezoneCairo is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Cairo, Egypt, which is "Africa/Cairo".
	DefaultTimezoneCairo ZoneRFC = "Africa/Cairo"

	// DefaultTimezoneAthens is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Athens, Greece, which is "Europe/Athens".
	DefaultTimezoneAthens ZoneRFC = "Europe/Athens"

	// DefaultTimezoneRome is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Rome, Italy, which is "Europe/Rome".
	DefaultTimezoneRome ZoneRFC = "Europe/Rome"

	// DefaultTimezoneJohannesburg is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Johannesburg, South Africa, which is "Africa/Johannesburg".
	DefaultTimezoneJohannesburg ZoneRFC = "Africa/Johannesburg"

	// DefaultTimezoneStockholm is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Stockholm, Sweden, which is "Europe/Stockholm".
	DefaultTimezoneStockholm ZoneRFC = "Europe/Stockholm"

	// DefaultTimezoneOslo is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Oslo, Norway, which is "Europe/Oslo".
	DefaultTimezoneOslo ZoneRFC = "Europe/Oslo"

	// DefaultTimezoneHelsinki is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Helsinki, Finland, which is "Europe/Helsinki".
	DefaultTimezoneHelsinki ZoneRFC = "Europe/Helsinki"

	// DefaultTimezoneKiev is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Kiev, Ukraine, which is "Europe/Kiev".
	DefaultTimezoneKiev ZoneRFC = "Europe/Kiev"

	// DefaultTimezoneBeijing is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Beijing, China, which is "Asia/Shanghai".
	DefaultTimezoneBeijing ZoneRFC = "Asia/Shanghai"

	// DefaultTimezoneSingapore is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Singapore, which is "Asia/Singapore".
	DefaultTimezoneSingapore ZoneRFC = "Asia/Singapore"

	// DefaultTimezoneIslamabad is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Islamabad, Pakistan, which is "Asia/Karachi".
	DefaultTimezoneIslamabad ZoneRFC = "Asia/Karachi"

	// DefaultTimezoneColombo is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Colombo, Sri Lanka, which is "Asia/Colombo".
	DefaultTimezoneColombo ZoneRFC = "Asia/Colombo"

	// DefaultTimezoneDhaka is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Dhaka, Bangladesh, which is "Asia/Dhaka".
	DefaultTimezoneDhaka ZoneRFC = "Asia/Dhaka"

	// DefaultTimezoneKathmandu is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Kathmandu, Nepal, which is "Asia/Kathmandu".
	DefaultTimezoneKathmandu ZoneRFC = "Asia/Kathmandu"

	// DefaultTimezoneBrisbane is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Brisbane, Australia, which is "Australia/Brisbane".
	DefaultTimezoneBrisbane ZoneRFC = "Australia/Brisbane"

	// DefaultTimezoneWellington is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Wellington, New Zealand, which is "Pacific/Auckland".
	DefaultTimezoneWellington ZoneRFC = "Pacific/Auckland"

	// DefaultTimezonePortMoresby is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Port Moresby, Papua New Guinea, which is "Pacific/Port_Moresby".
	DefaultTimezonePortMoresby ZoneRFC = "Pacific/Port_Moresby"

	// DefaultTimezoneSuva is a constant that holds the IANA Time Zone identifier
	// for the default timezone in Suva, Fiji, which is "Pacific/Fiji".
	DefaultTimezoneSuva ZoneRFC = "Pacific/Fiji"
)

Timezone constants representing default timezones for specific regions.

Directories

Path Synopsis
cmd
timefy command
examples
audit command
Package main demonstrates an enterprise audit-trail system using timefy.
Package main demonstrates an enterprise audit-trail system using timefy.
billing command
Package main demonstrates enterprise-grade SaaS subscription billing period calculations using the timefy library.
Package main demonstrates enterprise-grade SaaS subscription billing period calculations using the timefy library.
global_team command
Package main demonstrates multi-timezone global team coordination using the timefy library.
Package main demonstrates multi-timezone global team coordination using the timefy library.
reporting command
Package main demonstrates financial quarter and fiscal-year reporting using the timefy library.
Package main demonstrates financial quarter and fiscal-year reporting using the timefy library.
scheduler command
Package main demonstrates a business-day-aware job scheduler using timefy.
Package main demonstrates a business-day-aware job scheduler using timefy.

Jump to

Keyboard shortcuts

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