Skip to content

Instantly share code, notes, and snippets.

@emad-elsaid
Last active June 19, 2022 23:02
Show Gist options
  • Save emad-elsaid/cc026f69d1d73cdb9d87eb3e8931c7d1 to your computer and use it in GitHub Desktop.
Save emad-elsaid/cc026f69d1d73cdb9d87eb3e8931c7d1 to your computer and use it in GitHub Desktop.

Revisions

  1. emad-elsaid revised this gist Jun 19, 2022. 1 changed file with 3 additions and 12 deletions.
    15 changes: 3 additions & 12 deletions ago.go
    Original file line number Diff line number Diff line change
    @@ -1,24 +1,15 @@
    func ago(t time.Duration) string {
    o := ""

    t = t.Round(time.Second)
    func ago(t time.Duration) (o string) {
    const day = time.Hour * 24
    const week = day * 7
    const month = day * 30
    const year = day * 365
    const maxPrecision = 2
    precision := 0

    if t.Seconds() == 0 {
    if t.Seconds() < 1 {
    return "seconds ago"
    }

    for t.Seconds() > 0 {
    if precision >= maxPrecision {
    break
    }

    precision++
    for precision := 0; t.Seconds() > 0 && precision < maxPrecision; precision++ {
    switch {
    case t >= year:
    years := t / year
  2. emad-elsaid revised this gist Jun 19, 2022. No changes.
  3. emad-elsaid revised this gist Jun 19, 2022. No changes.
  4. emad-elsaid revised this gist Jun 19, 2022. No changes.
  5. emad-elsaid created this gist Jun 19, 2022.
    55 changes: 55 additions & 0 deletions ago.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    func ago(t time.Duration) string {
    o := ""

    t = t.Round(time.Second)
    const day = time.Hour * 24
    const week = day * 7
    const month = day * 30
    const year = day * 365
    const maxPrecision = 2
    precision := 0

    if t.Seconds() == 0 {
    return "seconds ago"
    }

    for t.Seconds() > 0 {
    if precision >= maxPrecision {
    break
    }

    precision++
    switch {
    case t >= year:
    years := t / year
    t -= years * year
    o += fmt.Sprintf("%d years ", years)
    case t >= month:
    months := t / month
    t -= months * month
    o += fmt.Sprintf("%d months ", months)
    case t >= week:
    weeks := t / week
    t -= weeks * week
    o += fmt.Sprintf("%d weeks ", weeks)
    case t >= day:
    days := t / day
    t -= days * day
    o += fmt.Sprintf("%d days ", days)
    case t >= time.Hour:
    hours := t / time.Hour
    t -= hours * time.Hour
    o += fmt.Sprintf("%d hours ", hours)
    case t >= time.Minute:
    minutes := t / time.Minute
    t -= minutes * time.Minute
    o += fmt.Sprintf("%d minutes ", minutes)
    case t >= time.Second:
    seconds := t / time.Second
    t -= seconds * time.Second
    o += fmt.Sprintf("%d seconds ", seconds)
    }
    }

    return o + "ago"
    }