humanize

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2023 License: BSD-3-Clause, MIT Imports: 15 Imported by: 1

Documentation

Overview

Package humanize provides a collection of functions to convert Go data structures into a human-readable format.

It was adopted in large part by the Django project and is therefore able to translate into several languages. A list of all supported languages can be found in the locale package.

Usage

Create a collection with the languages you want to use.

collection := humanize.MustNew(
    humanize.WithLocale(es.New(), ar.New(), zhHans.New()),
)

Create a humanizer

h := collection.CreateHumanizer(language.Spanish)

Use it

fmt.Println(h.Intword(1_000_000_000))
// Output: 1,0 millardo

Index

Examples

Constants

View Source
const (
	// DateFormat is the formatting to use for displaying dates
	// Fallback: 'N j, Y' (e.g. Feb. 4, 2003).
	DateFormat = "DATE_FORMAT"
	// TimeFormat is the formatting to use for displaying time
	// Fallback: 'P' (e.g. 4 p.m.)
	TimeFormat = "TIME_FORMAT"
	// DateTimeFormat is the formatting to use for displaying datetime
	// Fallback: 'N j, Y, P' (e.g. Feb. 4, 2003, 4 p.m.)
	DateTimeFormat = "DATETIME_FORMAT"
	// YearMonthFormat is suitable for cases when only the year and month should be displayed.
	// Fallback: 'F Y'.
	YearMonthFormat = "YEAR_MONTH_FORMAT"
	// MonthDayFormat is suitable for cases when only the month and day should be displayed.
	// Fallback 'F j'.
	MonthDayFormat = "MONTH_DAY_FORMAT"
	// ShortDateFormat
	// Fallback: 'm/d/Y' (e.g. 12/31/2003).
	ShortDateFormat = "SHORT_DATE_FORMAT"
	// ShortDatetimeFormat
	// Fallback: 'm/d/Y P' (e.g. 12/31/2003 4 p.m.)
	ShortDatetimeFormat = "SHORT_DATETIME_FORMAT"
)

Keywords for selecting a predefined formatting for a language when using FormatTime.

Variables

View Source
var LocaleInfos = map[string]LocaleInfo{
	"af": {
		Code:      "af",
		Name:      "Afrikaans",
		NameLocal: "Afrikaans",
	},
	"ar": {
		Code:      "ar",
		Name:      "Arabic",
		NameLocal: "العربيّة",
	},
	"ar-dz": {
		Code:      "ar-dz",
		Name:      "Algerian Arabic",
		NameLocal: "العربية الجزائرية",
	},
	"ast": {
		Code:      "ast",
		Name:      "Asturian",
		NameLocal: "asturianu",
	},
	"az": {
		Code:      "az",
		Name:      "Azerbaijani",
		NameLocal: "Azərbaycanca",
	},
	"be": {
		Code:      "be",
		Name:      "Belarusian",
		NameLocal: "беларуская",
	},
	"bg": {
		Code:      "bg",
		Name:      "Bulgarian",
		NameLocal: "български",
	},
	"bn": {
		Code:      "bn",
		Name:      "Bengali",
		NameLocal: "বাংলা",
	},
	"br": {
		Code:      "br",
		Name:      "Breton",
		NameLocal: "brezhoneg",
	},
	"bs": {
		Code:      "bs",
		Name:      "Bosnian",
		NameLocal: "bosanski",
	},
	"ca": {
		Code:      "ca",
		Name:      "Catalan",
		NameLocal: "català",
	},
	"ckb": {
		Code:      "ckb",
		Name:      "Central Kurdish (Sorani)",
		NameLocal: "کوردی",
	},
	"cs": {
		Code:      "cs",
		Name:      "Czech",
		NameLocal: "česky",
	},
	"cy": {
		Code:      "cy",
		Name:      "Welsh",
		NameLocal: "Cymraeg",
	},
	"da": {
		Code:      "da",
		Name:      "Danish",
		NameLocal: "dansk",
	},
	"de": {
		Code:      "de",
		Name:      "German",
		NameLocal: "Deutsch",
	},
	"dsb": {
		Code:      "dsb",
		Name:      "Lower Sorbian",
		NameLocal: "dolnoserbski",
	},
	"el": {
		Code:      "el",
		Name:      "Greek",
		NameLocal: "Ελληνικά",
	},
	"en": {
		Code:      "en",
		Name:      "English",
		NameLocal: "English",
	},
	"en-au": {
		Code:      "en-au",
		Name:      "Australian English",
		NameLocal: "Australian English",
	},
	"en-gb": {
		Code:      "en-gb",
		Name:      "British English",
		NameLocal: "British English",
	},
	"eo": {
		Code:      "eo",
		Name:      "Esperanto",
		NameLocal: "Esperanto",
	},
	"es": {
		Code:      "es",
		Name:      "Spanish",
		NameLocal: "español",
	},
	"es-ar": {
		Code:      "es-ar",
		Name:      "Argentinian Spanish",
		NameLocal: "español de Argentina",
	},
	"es-co": {
		Code:      "es-co",
		Name:      "Colombian Spanish",
		NameLocal: "español de Colombia",
	},
	"es-mx": {
		Code:      "es-mx",
		Name:      "Mexican Spanish",
		NameLocal: "español de Mexico",
	},
	"es-ni": {
		Code:      "es-ni",
		Name:      "Nicaraguan Spanish",
		NameLocal: "español de Nicaragua",
	},
	"es-ve": {
		Code:      "es-ve",
		Name:      "Venezuelan Spanish",
		NameLocal: "español de Venezuela",
	},
	"et": {
		Code:      "et",
		Name:      "Estonian",
		NameLocal: "eesti",
	},
	"eu": {
		Code:      "eu",
		Name:      "Basque",
		NameLocal: "Basque",
	},
	"fa": {
		Code:      "fa",
		Name:      "Persian",
		NameLocal: "فارسی",
	},
	"fi": {
		Code:      "fi",
		Name:      "Finnish",
		NameLocal: "suomi",
	},
	"fr": {
		Code:      "fr",
		Name:      "French",
		NameLocal: "français",
	},
	"fy": {
		Code:      "fy",
		Name:      "Frisian",
		NameLocal: "frysk",
	},
	"ga": {
		Code:      "ga",
		Name:      "Irish",
		NameLocal: "Gaeilge",
	},
	"gd": {
		Code:      "gd",
		Name:      "Scottish Gaelic",
		NameLocal: "Gàidhlig",
	},
	"gl": {
		Code:      "gl",
		Name:      "Galician",
		NameLocal: "galego",
	},
	"he": {
		Code:      "he",
		Name:      "Hebrew",
		NameLocal: "עברית",
	},
	"hi": {
		Code:      "hi",
		Name:      "Hindi",
		NameLocal: "हिंदी",
	},
	"hr": {
		Code:      "hr",
		Name:      "Croatian",
		NameLocal: "Hrvatski",
	},
	"hsb": {
		Code:      "hsb",
		Name:      "Upper Sorbian",
		NameLocal: "hornjoserbsce",
	},
	"hu": {
		Code:      "hu",
		Name:      "Hungarian",
		NameLocal: "Magyar",
	},
	"hy": {
		Code:      "hy",
		Name:      "Armenian",
		NameLocal: "հայերեն",
	},
	"ia": {
		Code:      "ia",
		Name:      "Interlingua",
		NameLocal: "Interlingua",
	},
	"io": {
		Code:      "io",
		Name:      "Ido",
		NameLocal: "ido",
	},
	"id": {
		Code:      "id",
		Name:      "Indonesian",
		NameLocal: "Bahasa Indonesia",
	},
	"ig": {
		Code:      "ig",
		Name:      "Igbo",
		NameLocal: "Asụsụ Ìgbò",
	},
	"is": {
		Code:      "is",
		Name:      "Icelandic",
		NameLocal: "Íslenska",
	},
	"it": {
		Code:      "it",
		Name:      "Italian",
		NameLocal: "italiano",
	},
	"ja": {
		Code:      "ja",
		Name:      "Japanese",
		NameLocal: "日本語",
	},
	"ka": {
		Code:      "ka",
		Name:      "Georgian",
		NameLocal: "ქართული",
	},
	"kab": {
		Code:      "kab",
		Name:      "Kabyle",
		NameLocal: "taqbaylit",
	},
	"kk": {
		Code:      "kk",
		Name:      "Kazakh",
		NameLocal: "Қазақ",
	},
	"km": {
		Code:      "km",
		Name:      "Khmer",
		NameLocal: "Khmer",
	},
	"kn": {
		Code:      "kn",
		Name:      "Kannada",
		NameLocal: "Kannada",
	},
	"ko": {
		Code:      "ko",
		Name:      "Korean",
		NameLocal: "한국어",
	},
	"ky": {
		Code:      "ky",
		Name:      "Kyrgyz",
		NameLocal: "Кыргызча",
	},
	"lb": {
		Code:      "lb",
		Name:      "Luxembourgish",
		NameLocal: "Lëtzebuergesch",
	},
	"lt": {
		Code:      "lt",
		Name:      "Lithuanian",
		NameLocal: "Lietuviškai",
	},
	"lv": {
		Code:      "lv",
		Name:      "Latvian",
		NameLocal: "latviešu",
	},
	"mk": {
		Code:      "mk",
		Name:      "Macedonian",
		NameLocal: "Македонски",
	},
	"ml": {
		Code:      "ml",
		Name:      "Malayalam",
		NameLocal: "മലയാളം",
	},
	"mn": {
		Code:      "mn",
		Name:      "Mongolian",
		NameLocal: "Mongolian",
	},
	"mr": {
		Code:      "mr",
		Name:      "Marathi",
		NameLocal: "मराठी",
	},
	"ms": {
		Code:      "ms",
		Name:      "Malay",
		NameLocal: "Bahasa Melayu",
	},
	"my": {
		Code:      "my",
		Name:      "Burmese",
		NameLocal: "မြန်မာဘာသာ",
	},
	"nb": {
		Code:      "nb",
		Name:      "Norwegian Bokmal",
		NameLocal: "norsk (bokmål)",
	},
	"ne": {
		Code:      "ne",
		Name:      "Nepali",
		NameLocal: "नेपाली",
	},
	"nl": {
		Code:      "nl",
		Name:      "Dutch",
		NameLocal: "Nederlands",
	},
	"nn": {
		Code:      "nn",
		Name:      "Norwegian Nynorsk",
		NameLocal: "norsk (nynorsk)",
	},
	"no": {
		Code:      "no",
		Name:      "Norwegian",
		NameLocal: "norsk",
	},
	"os": {
		Code:      "os",
		Name:      "Ossetic",
		NameLocal: "Ирон",
	},
	"pa": {
		Code:      "pa",
		Name:      "Punjabi",
		NameLocal: "Punjabi",
	},
	"pl": {
		Code:      "pl",
		Name:      "Polish",
		NameLocal: "polski",
	},
	"pt": {
		Code:      "pt",
		Name:      "Portuguese",
		NameLocal: "Português",
	},
	"pt-br": {
		Code:      "pt-br",
		Name:      "Brazilian Portuguese",
		NameLocal: "Português Brasileiro",
	},
	"ro": {
		Code:      "ro",
		Name:      "Romanian",
		NameLocal: "Română",
	},
	"ru": {
		Code:      "ru",
		Name:      "Russian",
		NameLocal: "Русский",
	},
	"sk": {
		Code:      "sk",
		Name:      "Slovak",
		NameLocal: "Slovensky",
	},
	"sl": {
		Code:      "sl",
		Name:      "Slovenian",
		NameLocal: "Slovenščina",
	},
	"sq": {
		Code:      "sq",
		Name:      "Albanian",
		NameLocal: "shqip",
	},
	"sr": {
		Code:      "sr",
		Name:      "Serbian",
		NameLocal: "српски",
	},
	"sr-latn": {
		Code:      "sr-latn",
		Name:      "Serbian Latin",
		NameLocal: "srpski (latinica)",
	},
	"sv": {
		Code:      "sv",
		Name:      "Swedish",
		NameLocal: "svenska",
	},
	"sw": {
		Code:      "sw",
		Name:      "Swahili",
		NameLocal: "Kiswahili",
	},
	"ta": {
		Code:      "ta",
		Name:      "Tamil",
		NameLocal: "தமிழ்",
	},
	"te": {
		Code:      "te",
		Name:      "Telugu",
		NameLocal: "తెలుగు",
	},
	"tg": {
		Code:      "tg",
		Name:      "Tajik",
		NameLocal: "тоҷикӣ",
	},
	"th": {
		Code:      "th",
		Name:      "Thai",
		NameLocal: "ภาษาไทย",
	},
	"tk": {
		Code:      "tk",
		Name:      "Turkmen",
		NameLocal: "Türkmençe",
	},
	"tr": {
		Code:      "tr",
		Name:      "Turkish",
		NameLocal: "Türkçe",
	},
	"tt": {
		Code:      "tt",
		Name:      "Tatar",
		NameLocal: "Татарча",
	},
	"udm": {
		Code:      "udm",
		Name:      "Udmurt",
		NameLocal: "Удмурт",
	},
	"ug": {
		Code:      "ug",
		Name:      "Uyghur",
		NameLocal: "ئۇيغۇرچە",
	},
	"uk": {
		Code:      "uk",
		Name:      "Ukrainian",
		NameLocal: "Українська",
	},
	"ur": {
		Code:      "ur",
		Name:      "Urdu",
		NameLocal: "اردو",
	},
	"uz": {
		Code:      "uz",
		Name:      "Uzbek",
		NameLocal: "oʻzbek tili",
	},
	"vi": {
		Code:      "vi",
		Name:      "Vietnamese",
		NameLocal: "Tiếng Việt",
	},
	"zh-hans": {
		Code:      "zh-hans",
		Name:      "Simplified Chinese",
		NameLocal: "简体中文",
	},
	"zh-hant": {
		Code:      "zh-hant",
		Name:      "Traditional Chinese",
		NameLocal: "繁體中文",
	},
}

Functions

This section is empty.

Types

type Collection added in v0.2.2

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

Collection data structure which collects the translations and can create humanizers.

func MustNew

func MustNew(opts ...Option) *Collection

MustNew is similar to New except it panics if an error happens.

func New

func New(opts ...Option) (*Collection, error)

New creates a new Collection which holds the humanizers for the selected locales.

func (*Collection) CreateHumanizer added in v0.2.2

func (p *Collection) CreateHumanizer(lang ...interface{}) *Humanizer

CreateHumanizer creates a new humanizer. Multiple languages can be passed and a spreak.Localizer is created which decides which language is used.

type FormatData

type FormatData struct {
	// DateFormat is the formatting to use for displaying dates
	// Fallback: 'N j, Y' (e.g. Feb. 4, 2003)
	DateFormat string
	// TimeFormat is the formatting to use for displaying time
	// Fallback: 'P' (e.g. 4 p.m.)
	TimeFormat string
	// DateTimeFormat is the formatting to use for displaying datetime
	// Fallback: 'N j, Y, P' (e.g. Feb. 4, 2003, 4 p.m.)
	DateTimeFormat string
	// YearMonthFormat is suitable for cases when only the year and month should be displayed.
	// Fallback: 'F Y'
	YearMonthFormat string
	// MonthDayFormat is suitable for cases when only the month and day should be displayed.
	// Fallback 'F j'
	MonthDayFormat string
	// Fallback: 'm/d/Y' (e.g. 12/31/2003)
	ShortDateFormat string
	// Fallback: 'm/d/Y P' (e.g. 12/31/2003 4 p.m.)
	ShortDatetimeFormat string
	// FirstDayOfWeek defines the day of the week on which the week starts.
	// e.d 0 = Sunday, 1 = Monday, etc...
	FirstDayOfWeek int
}

FormatData represents a collection of formatting rules that belongs to a language. For example, the formatting of a date for a language.

It is automatically provided when using a language from the locale package.

type Humanizer

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

A Humanizer represents a collection of functions for humanizing data structures for a chosen language.

func (*Humanizer) Apnumber

func (h *Humanizer) Apnumber(val interface{}) string

Apnumber returns for numbers 1-9, the number spelled out. Otherwise, return the number. This follows Associated Press style.

Valid inputs are all values that can be interpreted as a number.

Examples:

- 1 becomes one.

- 2 becomes two.

- 10 becomes 10.

Example
package main

import (
	"fmt"

	"golang.org/x/text/language"

	"github.com/vorlif/spreak/humanize"
	"github.com/vorlif/spreak/humanize/locale/de"
	"github.com/vorlif/spreak/humanize/locale/es"
	"github.com/vorlif/spreak/humanize/locale/zhHans"
)

func main() {
	collection := humanize.MustNew(humanize.WithLocale(es.New(), de.New(), zhHans.New()))

	for _, tag := range []language.Tag{language.English, language.German, language.Spanish, language.SimplifiedChinese} {
		h := collection.CreateHumanizer(tag)
		fmt.Println(h.Apnumber(5))
	}
}
Output:

five
fünf
cinco
五

func (*Humanizer) Date

func (h *Humanizer) Date() string

Date returns the current date. Short form for FormatTime(time.Now(), DateFormat).

Example
package main

import (
	"fmt"

	"golang.org/x/text/language"

	"github.com/vorlif/spreak/humanize"
	"github.com/vorlif/spreak/humanize/locale/de"
	"github.com/vorlif/spreak/humanize/locale/es"
	"github.com/vorlif/spreak/humanize/locale/it"
)

func main() {
	collection := humanize.MustNew(humanize.WithLocale(es.New(), it.New(), de.New()))

	for _, tag := range []language.Tag{language.English, language.Italian, language.German} {
		h := collection.CreateHumanizer(tag)
		fmt.Println(h.Date())
	}
	// May 16, 2022
	// 16 Maggio 2022
	// 16. Mai 2022
}
Output:

func (*Humanizer) FilesizeFormat

func (h *Humanizer) FilesizeFormat(v interface{}) string

FilesizeFormat format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc.).

Valid inputs are byte arrays or any numeric value. For all other inputs, a string is returned with an error message in fmt style.

Example
package main

import (
	"fmt"
	"math"

	"golang.org/x/text/language"

	"github.com/vorlif/spreak/humanize"
	"github.com/vorlif/spreak/humanize/locale/de"
	"github.com/vorlif/spreak/humanize/locale/es"
	"github.com/vorlif/spreak/humanize/locale/zhHans"
)

func main() {
	collection := humanize.MustNew(humanize.WithLocale(es.New(), zhHans.New(), de.New()))

	for _, tag := range []language.Tag{language.English, language.SimplifiedChinese, language.German} {
		h := collection.CreateHumanizer(tag)
		fmt.Println(h.FilesizeFormat(make([]byte, 1000)))
		fmt.Println(h.FilesizeFormat(math.Pow(1024, 3)))
	}
}
Output:

1,000 bytes
1 GB
1,000 字节
1 GB
1.000 Bytes
1 GB

func (*Humanizer) FormatTime

func (h *Humanizer) FormatTime(t time.Time, format string) string

FormatTime formats a time according to the given format. The format string should be use the Django date format syntax, see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date

Pre-defined keywords for selecting a predefined formatting for a language are: humanize.DateFormat, humanize.TimeFormat, humanize.DateTimeFormat, humanize.YearMonthFormat, humanize.MonthDayFormat, humanize.ShortDateFormat and humanize.ShortDatetimeFormat. The output of the predefined formats depend on the language used.

Example
package main

import (
	"fmt"
	"time"

	"golang.org/x/text/language"

	"github.com/vorlif/spreak/humanize"
	"github.com/vorlif/spreak/humanize/locale/be"
	"github.com/vorlif/spreak/humanize/locale/de"
	"github.com/vorlif/spreak/humanize/locale/es"
)

func main() {
	collection := humanize.MustNew(humanize.WithLocale(es.New(), be.New(), de.New()))

	now := time.Date(2022, 05, 15, 18, 0, 0, 0, time.Local)
	for _, tag := range []language.Tag{language.English, language.MustParse("be"), language.German} {
		h := collection.CreateHumanizer(tag)
		fmt.Println(h.FormatTime(now, humanize.DateTimeFormat))
	}
}
Output:

May 15, 2022, 6 p.m.
траўня 15, 2022, 6 папаўдні
15. Mai 2022 18:00
Example (ShortDate)
package main

import (
	"fmt"
	"time"

	"golang.org/x/text/language"

	"github.com/vorlif/spreak/humanize"
	"github.com/vorlif/spreak/humanize/locale/de"
	"github.com/vorlif/spreak/humanize/locale/es"
	"github.com/vorlif/spreak/humanize/locale/zhHans"
)

func main() {
	collection := humanize.MustNew(humanize.WithLocale(es.New(), zhHans.New(), de.New()))

	now := time.Date(2022, 05, 15, 18, 0, 0, 0, time.Local)
	for _, tag := range []language.Tag{language.English, language.SimplifiedChinese, language.German} {
		h := collection.CreateHumanizer(tag)
		fmt.Println(h.FormatTime(now, humanize.ShortDateFormat))
	}
}
Output:

05/15/2022
2022年5月15日
15.05.2022
Example (ShortDateTime)
package main

import (
	"fmt"
	"time"

	"golang.org/x/text/language"

	"github.com/vorlif/spreak/humanize"
	"github.com/vorlif/spreak/humanize/locale/de"
	"github.com/vorlif/spreak/humanize/locale/es"
	"github.com/vorlif/spreak/humanize/locale/zhHans"
)

func main() {
	collection := humanize.MustNew(humanize.WithLocale(es.New(), zhHans.New(), de.New()))

	now := time.Date(2022, 05, 15, 18, 0, 0, 0, time.Local)
	for _, tag := range []language.Tag{language.English, language.SimplifiedChinese, language.German} {
		h := collection.CreateHumanizer(tag)
		fmt.Println(h.FormatTime(now, humanize.ShortDatetimeFormat))
	}
}
Output:

05/15/2022 6 p.m.
2022年5月15日 18:00
15.05.2022 18:00

func (*Humanizer) Intcomma

func (h *Humanizer) Intcomma(i interface{}) string

Intcomma converts an integer to a string containing commas every three digits. For example, 3000 becomes '3,000' and 45000 becomes '45,000'.

Valid inputs are all values that can be interpreted as a number.

Example
package main

import (
	"fmt"

	"golang.org/x/text/language"

	"github.com/vorlif/spreak/humanize"
	"github.com/vorlif/spreak/humanize/locale/de"
	"github.com/vorlif/spreak/humanize/locale/es"
	"github.com/vorlif/spreak/humanize/locale/zhHans"
)

func main() {
	collection := humanize.MustNew(humanize.WithLocale(es.New(), de.New(), zhHans.New()))

	for _, tag := range []language.Tag{language.English, language.Spanish, language.SimplifiedChinese} {
		h := collection.CreateHumanizer(tag)
		fmt.Println(h.Intcomma(1_000_000_000))
	}
}
Output:

1,000,000,000
1.000.000.000
1,000,000,000

func (*Humanizer) Intword

func (h *Humanizer) Intword(i interface{}) string

Intword convert a large integer to a friendly text representation. Works best for numbers over 1 million. For example, 1000000 becomes '1.0 million', 1200000 becomes '1.2 million' and '1200000000' becomes '1.2 billion'. Values up to 10^100 (Googol) are supported.

Translates 1.0 as a singular phrase and all other numeric values as plural, this may be incorrect for some languages. Works best for numbers over 1 million.

Valid inputs are all values that can be interpreted as a number.

Example
package main

import (
	"fmt"

	"golang.org/x/text/language"

	"github.com/vorlif/spreak/humanize"
	"github.com/vorlif/spreak/humanize/locale/de"
	"github.com/vorlif/spreak/humanize/locale/es"
	"github.com/vorlif/spreak/humanize/locale/zhHans"
)

func main() {
	collection := humanize.MustNew(humanize.WithLocale(es.New(), de.New(), zhHans.New()))

	for _, tag := range []language.Tag{language.English, language.Spanish, language.SimplifiedChinese} {
		h := collection.CreateHumanizer(tag)
		fmt.Println(h.Intword(1_000_000_000))
	}
}
Output:

1.0 billion
1,0 millardo
1.0 十亿

func (*Humanizer) Language

func (h *Humanizer) Language() language.Tag

Language returns the currently used language.

func (*Humanizer) LanguageName

func (h *Humanizer) LanguageName(lang string) string

LanguageName returns the name of the spoken language as called by the languages used.

If no translation exists for the name of the language, the input is returned.

Example
package main

import (
	"fmt"

	"golang.org/x/text/language"

	"github.com/vorlif/spreak/humanize"
	"github.com/vorlif/spreak/humanize/locale/de"
	"github.com/vorlif/spreak/humanize/locale/es"
	"github.com/vorlif/spreak/humanize/locale/zhHans"
)

func main() {
	collection := humanize.MustNew(humanize.WithLocale(es.New(), de.New(), zhHans.New()))

	for _, tag := range []language.Tag{language.English, language.Spanish, language.SimplifiedChinese} {
		h := collection.CreateHumanizer(tag)
		fmt.Printf("Examples in: %s, %s", h.LanguageName("English"), h.LanguageName("Spanish"))
		fmt.Printf(" and %s\n", h.LanguageName("Simplified Chinese"))
	}
}
Output:

Examples in: English, Spanish and Simplified Chinese
Examples in: Inglés, Español and Chino simplificado
Examples in: 英语, 西班牙语 and 简体中文

func (*Humanizer) LanguageNameByCode added in v0.6.0

func (h *Humanizer) LanguageNameByCode(code string) string

LanguageNameByCode returns the name of a language for a language code in the national language of the Humanizer.

If no language is known for the code, an empty string is returned. If a language is known, but no translations are available, the English name is returned.

For example, if a Humanizer was created for French, 'Anglais' is returned for the code 'en' and the value 'Allemand' for the code 'de'.

Example
package main

import (
	"fmt"
	"strings"

	"golang.org/x/text/language"

	"github.com/vorlif/spreak/humanize"
	"github.com/vorlif/spreak/humanize/locale/de"
	"github.com/vorlif/spreak/humanize/locale/es"
	"github.com/vorlif/spreak/humanize/locale/zhHans"
)

func main() {
	collection := humanize.MustNew(humanize.WithLocale(es.New(), zhHans.New(), de.New()))
	for _, tag := range []language.Tag{language.English, language.SimplifiedChinese, language.Spanish} {
		h := collection.CreateHumanizer(tag)
		fmt.Println("Current language: ", h.Language())

		for _, code := range []string{"de", "en"} {
			fmt.Printf("%s: %s\n", code, h.LanguageNameByCode(code))
		}

		fmt.Println(strings.Repeat(" -", 20))
	}
}
Output:

Current language:  en
de: German
en: English
 - - - - - - - - - - - - - - - - - - - -
Current language:  zh-Hans
de: 德语
en: 英语
 - - - - - - - - - - - - - - - - - - - -
Current language:  es
de: Alemán
en: Inglés
 - - - - - - - - - - - - - - - - - - - -

func (*Humanizer) NaturalDay

func (h *Humanizer) NaturalDay(i interface{}) string

NaturalDay returns for time values that are tomorrow, today or yesterday compared to present day the representing string. Any other time is formatted according to the defined DateFormat.

Valid inputs are time.Time, time.Duration or any numeric value which is interpreted as seconds since the Unix epoch. For all other inputs, a string is returned with an error message in fmt style.

Example
package main

import (
	"fmt"
	"time"

	"golang.org/x/text/language"

	"github.com/vorlif/spreak/humanize"
	"github.com/vorlif/spreak/humanize/locale/de"
	"github.com/vorlif/spreak/humanize/locale/es"
	"github.com/vorlif/spreak/humanize/locale/zhHans"
)

func main() {
	collection := humanize.MustNew(humanize.WithLocale(es.New(), de.New(), zhHans.New()))

	for _, tag := range []language.Tag{language.English, language.Spanish, language.SimplifiedChinese} {
		h := collection.CreateHumanizer(tag)
		fmt.Println(h.NaturalDay(time.Now()))
	}

	fmt.Println("---")

	d := time.Date(2022, 05, 01, 0, 0, 0, 0, time.UTC)
	for _, tag := range []language.Tag{language.English, language.Spanish, language.SimplifiedChinese} {
		h := collection.CreateHumanizer(tag)
		fmt.Println(h.NaturalDay(d))
	}
}
Output:

today
hoy
今天
---
May 1, 2022
1 de mayo de 2022
2022年5月1日

func (*Humanizer) NaturalTime

func (h *Humanizer) NaturalTime(i interface{}) string

NaturalTime shows for a time value how many seconds, minutes, or hours ago compared to current timestamp return representing string.

Valid inputs are time.Time, time.Duration or any numeric value which is interpreted as seconds since the Unix epoch. For all other inputs, a string is returned with an error message in fmt style.

Example
package main

import (
	"fmt"
	"time"

	"golang.org/x/text/language"

	"github.com/vorlif/spreak/humanize"
	"github.com/vorlif/spreak/humanize/locale/ar"
	"github.com/vorlif/spreak/humanize/locale/es"
	"github.com/vorlif/spreak/humanize/locale/zhHans"
)

func main() {
	collection := humanize.MustNew(humanize.WithLocale(es.New(), ar.New(), zhHans.New()))

	for _, tag := range []language.Tag{language.English, language.Arabic, language.SimplifiedChinese} {
		h := collection.CreateHumanizer(tag)
		t := time.Now().Add(5 * time.Minute)
		fmt.Println(h.NaturalTime(t))
	}
}
Output:

5 minutes from now
٥ دقائق من الآن
5分钟以后
Example (Past)
package main

import (
	"fmt"
	"time"

	"golang.org/x/text/language"

	"github.com/vorlif/spreak/humanize"
	"github.com/vorlif/spreak/humanize/locale/ar"
	"github.com/vorlif/spreak/humanize/locale/es"
	"github.com/vorlif/spreak/humanize/locale/zhHans"
)

func main() {
	collection := humanize.MustNew(humanize.WithLocale(es.New(), ar.New(), zhHans.New()))

	for _, tag := range []language.Tag{language.English, language.Arabic, language.SimplifiedChinese} {
		h := collection.CreateHumanizer(tag)
		t := time.Now().Add(-2*time.Hour - 30*time.Minute)
		fmt.Println(h.NaturalTime(t))
	}
}
Output:

2 hours ago
منذ ٢ ساعة
2小时之前

func (*Humanizer) Now

func (h *Humanizer) Now() string

Now returns the current date and time. Short form for FormatTime(time.Now(), DateTimeFormat).

Example
package main

import (
	"fmt"

	"golang.org/x/text/language"

	"github.com/vorlif/spreak/humanize"
	"github.com/vorlif/spreak/humanize/locale/de"
	"github.com/vorlif/spreak/humanize/locale/es"
	"github.com/vorlif/spreak/humanize/locale/it"
)

func main() {
	collection := humanize.MustNew(humanize.WithLocale(es.New(), it.New(), de.New()))

	for _, tag := range []language.Tag{language.English, language.Italian, language.German} {
		h := collection.CreateHumanizer(tag)
		fmt.Println(h.Now())
	}
	// May 16, 2022, 12:34 a.m.
	// Lunedì 16 Maggio 2022 00:34
	// 16. Mai 2022 00:34
}
Output:

func (*Humanizer) Ordinal

func (h *Humanizer) Ordinal(i interface{}) string

Ordinal converts an integer to its ordinal as a string. 1 is '1st', 2 is '2nd', 3 is '3rd', etc. Works for any integer.

Valid inputs are all values that can be interpreted as a number.

Example
package main

import (
	"fmt"

	"golang.org/x/text/language"

	"github.com/vorlif/spreak/humanize"
	"github.com/vorlif/spreak/humanize/locale/de"
	"github.com/vorlif/spreak/humanize/locale/es"
	"github.com/vorlif/spreak/humanize/locale/zhHans"
)

func main() {
	collection := humanize.MustNew(humanize.WithLocale(es.New(), de.New(), zhHans.New()))

	for _, tag := range []language.Tag{language.English, language.Spanish, language.SimplifiedChinese} {
		h := collection.CreateHumanizer(tag)
		fmt.Println(h.Ordinal(5))
	}
}
Output:

5th
5º
第5

func (*Humanizer) Time

func (h *Humanizer) Time() string

Time returns the current time. Short form for FormatTime(time.Now(), TimeFormat).

Example
package main

import (
	"fmt"

	"golang.org/x/text/language"

	"github.com/vorlif/spreak/humanize"
	"github.com/vorlif/spreak/humanize/locale/de"
	"github.com/vorlif/spreak/humanize/locale/es"
	"github.com/vorlif/spreak/humanize/locale/it"
)

func main() {
	collection := humanize.MustNew(humanize.WithLocale(es.New(), it.New(), de.New()))

	for _, tag := range []language.Tag{language.English, language.Italian, language.German} {
		h := collection.CreateHumanizer(tag)
		fmt.Println(h.Time())
	}
	// 12:30 a.m.
	// 00:30
	// 00:30
}
Output:

func (*Humanizer) TimeSince

func (h *Humanizer) TimeSince(inputTime interface{}, opts ...TimeOption) string

TimeSince take a time object and return the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, return "0 minutes".

Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored. Up to `depth` adjacent units will be displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not.

Valid inputs are time.Time, time.Duration or any numeric value which is interpreted as seconds since the Unix epoch. For all other inputs, a string is returned with an error message in fmt style.

Example
package main

import (
	"fmt"
	"time"

	"golang.org/x/text/language"

	"github.com/vorlif/spreak/humanize"
	"github.com/vorlif/spreak/humanize/locale/be"
	"github.com/vorlif/spreak/humanize/locale/de"
	"github.com/vorlif/spreak/humanize/locale/es"
)

func main() {
	collection := humanize.MustNew(humanize.WithLocale(es.New(), be.New(), de.New()))

	t := time.Now().Add(-37 * time.Hour)
	for _, tag := range []language.Tag{language.English, language.MustParse("be"), language.German} {
		h := collection.CreateHumanizer(tag)
		fmt.Println(h.TimeSince(t))
	}
}
Output:

1 day, 13 hours
1 дзень, 13 гадзін
1 Tag, 13 Stunden
Example (Duration)
package main

import (
	"fmt"
	"time"

	"golang.org/x/text/language"

	"github.com/vorlif/spreak/humanize"
	"github.com/vorlif/spreak/humanize/locale/be"
	"github.com/vorlif/spreak/humanize/locale/de"
	"github.com/vorlif/spreak/humanize/locale/es"
)

func main() {
	collection := humanize.MustNew(humanize.WithLocale(es.New(), be.New(), de.New()))

	t := -80 * time.Hour
	for _, tag := range []language.Tag{language.English, language.MustParse("be"), language.German} {
		h := collection.CreateHumanizer(tag)
		fmt.Println(h.TimeSince(t))
	}
}
Output:

3 days, 8 hours
3  дзён, 8 гадзін
3 Tage, 8 Stunden

func (*Humanizer) TimeSinceFrom

func (h *Humanizer) TimeSinceFrom(d interface{}, now time.Time, opts ...TimeOption) string

TimeSinceFrom works like TimeSince, but the time to use as the comparison point can be specified. Is equivalent to TimeSince(d, WithNow(now)).

func (*Humanizer) TimeUntil

func (h *Humanizer) TimeUntil(d interface{}, opts ...TimeOption) string

TimeUntil works similar to TimeSince, except that it measures the time from now until the given date or datetime. For example, if today is 1 June 2006 and conferenceDate is a date instance holding 29 June 2006, then TimeUntil(conferenceDate) will return “4 weeks”.

Example
package main

import (
	"fmt"
	"time"

	"golang.org/x/text/language"

	"github.com/vorlif/spreak/humanize"
	"github.com/vorlif/spreak/humanize/locale/be"
	"github.com/vorlif/spreak/humanize/locale/de"
	"github.com/vorlif/spreak/humanize/locale/es"
)

func main() {
	collection := humanize.MustNew(humanize.WithLocale(es.New(), be.New(), de.New()))

	t := time.Now().Add(37 * time.Hour)
	for _, tag := range []language.Tag{language.English, language.MustParse("be"), language.German} {
		h := collection.CreateHumanizer(tag)
		fmt.Println(h.TimeUntil(t))
	}
}
Output:

1 day, 13 hours
1 дзень, 13 гадзін
1 Tag, 13 Stunden

func (*Humanizer) TimeUntilFrom

func (h *Humanizer) TimeUntilFrom(d interface{}, now time.Time, opts ...TimeOption) string

TimeUntilFrom works like TimeUntil, but the time to use as the comparison point can be specified. Is equivalent to TimeUntil(d, WithNow(now)).

type LocaleData

type LocaleData struct {
	Lang   language.Tag
	Fs     fs.FS
	Format *FormatData
}

LocaleData represents a collection of information and data about a language.

type LocaleInfo added in v0.6.0

type LocaleInfo struct {
	Code      string
	Name      string
	NameLocal string
}

type Option

type Option func(opts *options) error

An Option that can be used to customize the configuration when creating a Collection.

func WithBundleOption

func WithBundleOption(opt spreak.BundleOption) Option

WithBundleOption Allows to store custom options for the internally created spreak.Bundle.

func WithLocale

func WithLocale(data ...*LocaleData) Option

WithLocale specifies which languages to support for humanization.

type TimeOption

type TimeOption func(opt *timeSinceOptions)

TimeOption allows to control the output of the time function.

func WithDepth

func WithDepth(depth int) TimeOption

WithDepth can be used to set the maximum number of time units to be displayed. Default value 2.

By default, only adjacent time units are displayed. For example, "1 week, 3 days" is a adjacent, but not "1 week, 3 hours". To disable this behavior, the WithoutAdjacentCheck option can be passed.

Example
package main

import (
	"fmt"
	"strings"
	"time"

	"golang.org/x/text/language"

	"github.com/vorlif/spreak/humanize"
	"github.com/vorlif/spreak/humanize/locale/be"
	"github.com/vorlif/spreak/humanize/locale/de"
	"github.com/vorlif/spreak/humanize/locale/es"
)

func main() {
	collection := humanize.MustNew(humanize.WithLocale(es.New(), be.New(), de.New()))

	t := -3080*time.Hour - 5*time.Minute
	for _, tag := range []language.Tag{language.English, language.MustParse("be"), language.German} {
		h := collection.CreateHumanizer(tag)
		fmt.Println(h.TimeSince(t, humanize.WithDepth(1), humanize.WithoutAdjacentCheck()))
		fmt.Println(h.TimeSince(t, humanize.WithoutAdjacentCheck())) // 2 is default
		fmt.Println(h.TimeSince(t, humanize.WithDepth(3), humanize.WithoutAdjacentCheck()))
		fmt.Println(h.TimeSince(t, humanize.WithDepth(4), humanize.WithoutAdjacentCheck()))
		fmt.Println(h.TimeSince(t, humanize.WithDepth(5), humanize.WithoutAdjacentCheck()))
		fmt.Println(strings.Repeat(" -", 20))
	}
}
Output:

4 months
4 months, 1 week
4 months, 1 week, 1 day
4 months, 1 week, 1 day, 8 hours
4 months, 1 week, 1 day, 8 hours, 5 minutes
 - - - - - - - - - - - - - - - - - - - -
4 месяцаў
4 месяцаў, 1 тыдзень
4 месяцаў, 1 тыдзень, 1 дзень
4 месяцаў, 1 тыдзень, 1 дзень, 8 гадзін
4 месяцаў, 1 тыдзень, 1 дзень, 8 гадзін, 5 хвілін
 - - - - - - - - - - - - - - - - - - - -
4 Monate
4 Monate, 1 Woche
4 Monate, 1 Woche, 1 Tag
4 Monate, 1 Woche, 1 Tag, 8 Stunden
4 Monate, 1 Woche, 1 Tag, 8 Stunden, 5 Minuten
 - - - - - - - - - - - - - - - - - - - -

func WithNow

func WithNow(now time.Time) TimeOption

WithNow allows to set the starting point of calculations. Default is time.Now().

Example
package main

import (
	"fmt"
	"time"

	"golang.org/x/text/language"

	"github.com/vorlif/spreak/humanize"
	"github.com/vorlif/spreak/humanize/locale/de"
	"github.com/vorlif/spreak/humanize/locale/es"
	"github.com/vorlif/spreak/humanize/locale/zhHans"
)

func main() {
	collection := humanize.MustNew(humanize.WithLocale(es.New(), zhHans.New(), de.New()))

	now := time.Date(1999, 12, 24, 00, 0, 0, 0, time.Local)
	event := time.Date(2000, 01, 01, 00, 0, 0, 0, time.Local)
	for _, tag := range []language.Tag{language.English, language.SimplifiedChinese, language.German} {
		h := collection.CreateHumanizer(tag)
		fmt.Println(h.TimeUntil(event, humanize.WithNow(now)))
	}
}
Output:

1 week, 1 day
1 周,1 日
1 Woche, 1 Tag

func WithReverse

func WithReverse(reverse bool) TimeOption

func WithoutAdjacentCheck added in v0.2.2

func WithoutAdjacentCheck() TimeOption

WithoutAdjacentCheck disables that only adjacent time units are output. By default, only adjacent time units are displayed. For example, "1 week, 3 days" is a adjacent, but not "1 week, 3 hours".

Directories

Path Synopsis
locale
af
ar
ast
az
be
bg
bn
br
bs
ca
ckb
cs
cy
da
de
dsb
el
eo
es
et
eu
fa
fi
fr
fy
ga
gd
gl
he
hi
hr
hsb
hu
hy
ia
id
ig
io
is
it
ja
ka
kab
kk
km
kn
ko
ky
lb
lt
lv
mk
ml
mn
mr
ms
my
nb
ne
nl
nn
os
pa
pl
pt
ro
ru
sk
sl
sq
sr
sv
sw
ta
te
tg
th
tk
tr
tt
udm
ug
uk
ur
uz
vi

Jump to

Keyboard shortcuts

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