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/moment

Quick 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 120

Features

  • Immutable Moment over time.Time — every method returns a new value; construct with New, FromTime, Now, Unix, UnixMilli or DateTime
  • moment-token Format and ParseFormat (YYYY/MMMM/dddd/HH…) with [literal] escaping, plus raw-layout FormatLayout/ParseLayout and forgiving Parse
  • Unit arithmetic — Add, Subtract, AddDuration, StartOf, EndOf and Set keyed by the Unit constants (YearMillisecond) with moment.js aliases
  • Comparison & query — IsBefore, IsAfter, IsSame, IsBetween, IsSameUnit and getters like Year, Weekday, DayOfYear, ISOWeek
  • Difference in any unit — Diff (float64), DiffInt (truncated) and DiffDuration (time.Duration), with moment.js-style fractional month math
  • Humanized relative time — FromNow, From, To, ToNow, Calendar and package-level Humanize ("in 3 days", "Today at 2:30 PM")
  • Deterministic clock — the injectable Clock interface with FixedClock and WithClock makes relative-time output reproducible in tests
  • Time zones — In, UTC and Local reinterpret a moment in another time.Location without changing the instant
  • Zero dependencies — pure Go standard library, no cgo, nothing to audit but the toolchain
Moment