prettytime

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2020 License: MIT Imports: 3 Imported by: 28

README

Go Pretty Time

Go Report Card Build Status GoDoc CodeCov

Format Go date time in a pretty way. ex : just now, a minute ago, 2 hours ago , 3 minutes ago

Inspired by the John Resig Pretty Date plug-in for JQuery

prettytime.Format("2008-01-28T20:24:17Z") // => "2 hours ago"
prettytime.Format("2008-01-27T22:24:17Z") // => "Yesterday"
prettytime.Format("2008-01-26T22:24:17Z") // => "2 days ago"
prettytime.Format("2008-01-14T22:24:17Z") // => "2 weeks ago"

Install

go get github.com/andanhm/go-prettytime
Example
package main

import (
	"log"
	"time"

	"github.com/andanhm/go-prettytime"
)

const (
	layout = "2006-01-02T15:04:05Z"
)

func main() {
	t, err := time.Parse(layout, "2008-01-28T20:24:17Z")
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("%s \n", prettytime.Format(t))
}
// Output: 13 years ago
Contributions

Feel free to fork and add features, fix bugs and your pull request is more than welcome ❤

Documentation

Overview

Package prettytime provides utility functions for calculating and presenting in human readable and understandable form.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Format

func Format(t time.Time) (timeSince string)

Format returns a string describing how long it has been since the time argument passed int

Example
timeSlots := []struct {
	name string
	t    time.Time
}{
	{name: "Just now", t: time.Now()},
	{name: "Second", t: time.Now().Add(
		time.Hour*time.Duration(0) +
			time.Minute*time.Duration(0) +
			time.Second*time.Duration(1)),
	},
	{name: "SecondAgo", t: time.Now().Add(
		time.Hour*time.Duration(0) +
			time.Minute*time.Duration(0) +
			time.Second*time.Duration(-1)),
	},
	{name: "Minutes", t: time.Now().Add(time.Hour*time.Duration(0) +
		time.Minute*time.Duration(59) +
		time.Second*time.Duration(59))},
	{name: "Tomorrow", t: time.Now().AddDate(0, 0, 1)},
	{name: "Yesterday", t: time.Now().AddDate(0, 0, -1)},
	{name: "Week", t: time.Now().AddDate(0, 0, 7)},
	{name: "WeekAgo", t: time.Now().AddDate(0, 0, -7)},
	{name: "Month", t: time.Now().AddDate(0, 1, 0)},
	{name: "MonthAgo", t: time.Now().AddDate(0, -1, 0)},
	{name: "Year", t: time.Now().AddDate(2, 0, 0)},
	{name: "YearAgo", t: time.Now().AddDate(-2, 0, 0)},
}

for _, timeSlot := range timeSlots {
	fmt.Printf("%s = %v\n", timeSlot.name, Format(timeSlot.t))
}
Output:

Types

This section is empty.

Jump to

Keyboard shortcuts

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