Moment for Go
github.com/malcolmston/moment
moment.js-style dates and times in Go.
GitHubports moment/moment
A from-scratch, standard-library-only Go take on moment.js, layered directly on the time package with no cgo and no third-party dependencies. A <code>Moment</code> is an immutable wrapper around <code>time.Time</code>: every manipulation method returns a new value and never mutates the receiver, so moments are safe to share. You get moment-token parsing and formatting (YYYY, MMMM, dddd, HH…), unit-based Add/Subtract/StartOf/EndOf/Set arithmetic, float and integer Diff, comparison and query helpers, timezone reinterpretation, and humanized relative time (FromNow, Calendar, Humanize) driven by an injectable Clock so tests stay deterministic. The import path and package name are both moment.
Install
shell
$ go get github.com/malcolmston/momentQuick start
main.go
import "github.com/malcolmston/moment"
// The import path and the package name are both moment.
m, _ := moment.ParseFormat("14/07/2017 02:40", "DD/MM/YYYY HH:mm")
fmt.Println(m.Format("dddd, MMMM D, YYYY [at] h:mm A"))
// Friday, July 14, 2017 at 2:40 AM
later := m.Add(2, moment.Hour)
fmt.Println(m.IsBefore(later), later.DiffInt(m, moment.Minute))
// true 120Features
- Immutable
Momentovertime.Time— every method returns a new value; construct withNew,FromTime,Now,Unix,UnixMilliorDateTime - moment-token
FormatandParseFormat(YYYY/MMMM/dddd/HH…) with[literal]escaping, plus raw-layoutFormatLayout/ParseLayoutand forgivingParse - Unit arithmetic —
Add,Subtract,AddDuration,StartOf,EndOfandSetkeyed by theUnitconstants (Year…Millisecond) with moment.js aliases - Comparison & query —
IsBefore,IsAfter,IsSame,IsBetween,IsSameUnitand getters likeYear,Weekday,DayOfYear,ISOWeek - Difference in any unit —
Diff(float64),DiffInt(truncated) andDiffDuration(time.Duration), with moment.js-style fractional month math - Humanized relative time —
FromNow,From,To,ToNow,Calendarand package-levelHumanize("in 3 days", "Today at 2:30 PM") - Deterministic clock — the injectable
Clockinterface withFixedClockandWithClockmakes relative-time output reproducible in tests - Time zones —
In,UTCandLocalreinterpret a moment in anothertime.Locationwithout changing the instant - Zero dependencies — pure Go standard library, no cgo, nothing to audit but the toolchain