repositorypackage
1.0.0
Repository: https://github.com/fallentaters/timefmt.git
Documentation: pkg.go.dev
# Packages
No description provided by the author
# README
timeftm
Date[F DateFormat]
A fully comparable date object that always formats to the specified format. Meant to be used for encoding when time is irrelevant.
Example
package main
import (
"encoding/json"
"fmt"
"time"
"github.com/FallenTaters/timefmt"
"github.com/FallenTaters/timefmt/formats/iso8601"
"github.com/FallenTaters/timefmt/formats/rfc3339"
)
type customFormat struct{}
func (customFormat) TimeFormat() string {
return `2006/01/02 03:04 PM`
}
func (customFormat) DateFormat() string {
return `02 Jan 2006`
}
type Payload struct {
Date timefmt.Date[customFormat] `json:"date"`
Time timefmt.Time[customFormat] `json:"time"`
}
func main() {
d := timefmt.NewDate[customFormat](2022, 7, 4)
fmt.Println(d) // 04 Jul 2022
t := timefmt.TimeFrom[customFormat](time.Date(2022, 7, 4, 16, 19, 59, 1_000_000_000, time.UTC))
fmt.Println(t) // 2022/07/04 04:20 PM
// json
jsonText := `{"date":"04 Jul 2022","time":"2022/07/04 04:20 PM"}`
var p Payload
err := json.Unmarshal([]byte(jsonText), &p)
if err != nil {
panic(err)
}
data, err := json.Marshal(p)
if err != nil {
panic(err)
}
fmt.Println(string(data) == jsonText) // true
// dates of different times are comparable
d1 := time.Date(2022, 7, 4, 0, 0, 0, 0, time.UTC)
d2 := d1.Add(time.Hour + time.Minute + time.Second)
fmt.Println(timefmt.DateFrom[customFormat](d1) == timefmt.DateFrom[customFormat](d2)) // true
}
// Some useful formats are predefined
type predefined struct {
ISO8601 iso8601.Date // YYYY-MM-DD
DayMonthYear timefmt.Date[timefmt.DayMonthYear] // DD/MM/YYYY
MonthDayYear timefmt.Date[timefmt.MonthDayYear] // MM/DD/YYYY
RFC3339 rfc3339.Time // 2006-01-02T15:04:05Z07:00
YearMonthDayTime timefmt.Time[timefmt.YearMonthDayTime] // YYYY-MM-DD HH:MM:SS
}
Description
-
Compatible with
encoding/*
- through
encoding.TextUnmarshaler
andencoding.TextMarshaler
- through
database/sql
anddatabase/sql/driver
- through
sql.Scanner
anddriver.Valuer
- through
-
Easy conversion
- types can be cast to each other to quickly convert between formats
-
Dates Comparable
- hour, minute, second, nanoseconds and timezone are stripped when using
DateFrom
- hour, minute, second, nanoseconds and timezone are stripped when using
-
Custom formats
- some formats predefined, see example above
- easy to define new format struct