Convert string to duration in golang

Go String To Duration (go-str2duration)

This package allows to get a time.Duration from a string. The string can be a string retorned for time.Duration or a similar string with weeks or days too!.

Go Report Card go.dev

Download

go get github.com/xhit/go-str2duration/v2

Features

Go String To Duration supports this strings conversions to duration:

  • All strings returned in time.Duration String.
  • A string more readable like 1w2d6h3ns (1 week 2 days 6 hours and 3 nanoseconds).
  • µs and us are microsecond.

It's the same time.ParseDuration standard function in Go, but with days and week support.

Note: a day is 24 hour.

If you don't need days and weeks, use time.ParseDuration.

Usage

package main

import (
	"fmt"
	str2duration "github.com/xhit/go-str2duration/v2"
	"os"
	"time"
)

func main() {

    for i, tt := range []struct {
            dur      string
            expected time.Duration
        }{
            //This times are returned with time.Duration string
            {"1h", time.Duration(time.Hour)},
            {"1m", time.Duration(time.Minute)},
            {"1s", time.Duration(time.Second)},
            {"1ms", time.Duration(time.Millisecond)},
            {"1µs", time.Duration(time.Microsecond)},
            {"1us", time.Duration(time.Microsecond)},
            {"1ns", time.Duration(time.Nanosecond)},
            {"4.000000001s", time.Duration(4*time.Second + time.Nanosecond)},
            {"1h0m4.000000001s", time.Duration(time.Hour + 4*time.Second + time.Nanosecond)},
            {"1h1m0.01s", time.Duration(61*time.Minute + 10*time.Millisecond)},
            {"1h1m0.123456789s", time.Duration(61*time.Minute + 123456789*time.Nanosecond)},
            {"1.00002ms", time.Duration(time.Millisecond + 20*time.Nanosecond)},
            {"1.00000002s", time.Duration(time.Second + 20*time.Nanosecond)},
            {"693ns", time.Duration(693 * time.Nanosecond)},

            //This times aren't returned with time.Duration string, but are easily readable and can be parsed too!
            {"1ms1ns", time.Duration(time.Millisecond + 1*time.Nanosecond)},
            {"1s20ns", time.Duration(time.Second + 20*time.Nanosecond)},
            {"60h8ms", time.Duration(60*time.Hour + 8*time.Millisecond)},
            {"96h63s", time.Duration(96*time.Hour + 63*time.Second)},

            //And works with days and weeks!
            {"2d3s96ns", time.Duration(48*time.Hour + 3*time.Second + 96*time.Nanosecond)},
            {"1w2d3s96ns", time.Duration(168*time.Hour + 48*time.Hour + 3*time.Second + 96*time.Nanosecond)},

            {"10s1us693ns", time.Duration(10*time.Second + time.Microsecond + 693*time.Nanosecond)},

        } {
            durationFromString, err := str2duration.ParseDuration(tt.dur)
            if err != nil {
                panic(err)

            //Check if expected time is the time returned by the parser
            } else if tt.expected != durationFromString {
                 fmt.Println(fmt.Sprintf("index %d -> in: %s returned: %s\tnot equal to %s", i, tt.dur, durationFromString.String(), tt.expected.String()))
            }else{
                fmt.Println(fmt.Sprintf("index %d -> in: %s parsed succesfully", i, tt.dur))
            }
        }
}
Owner
Santiago De la Cruz
Doing some private stuffs.
Santiago De la Cruz
Similar Resources

Go-timeparser - Flexible Time Parser for Golang

go-timeparser Flexible Time Parser for Golang Installation Download timeparser w

Dec 29, 2022

Convert string to duration in golang

Go String To Duration (go-str2duration) This package allows to get a time.Duration from a string. The string can be a string retorned for time.Duratio

Dec 7, 2022

:clock8: Better time duration formatting in Go!

durafmt durafmt is a tiny Go library that formats time.Duration strings (and types) into a human readable format. go get github.com/hako/durafmt Why

Dec 16, 2022

Copy of stdlib's time.Duration, but ParseDuration accepts other bigger units such as days, weeks, months and years

duration Copy of stdlib's time.Duration, but ParseDuration accepts other units as well: d: days (7 * 24 * time.Hour) w: weeks (7 * Day) mo: months (30

Jun 21, 2022

sleep command accepting Go duration syntax.

gsleep sleep command accepting Go duration syntax. Installation go install github.com/forestgagnon/gsleep@latest Usage # Sleep 5 minutes gsleep 5m #

Jan 14, 2022

Go rate limiter used to ensure a minimum duration between executions.

Ratelimiter Rate limiter used to ensure a minimum duration between executions. Additionally supports the optional limit of max queue size. This can be

Jul 14, 2022

Buffer Compactor is a tool to allow for buffering for a duration and compacting data on keys.

Buffer Compactor is a tool to allow for buffering for a duration and compacting data on keys. It uses a badgerDB and sortedset in order to coridinate a time-delayed queue that also aggregates updates sharing the same key in a extremely peformant manner.

Feb 8, 2022

Golang metrics for calculating string similarity and other string utility functions

strutil strutil provides string metrics for calculating string similarity as well as other string utility functions. Full documentation can be found a

Jan 3, 2023

Convert json string to Golang struct

json-to-go-cli Convert json string to Golang struct How to install git clone https://github.com/tiancheng92/json-to-go-cli.git cd json-to-go-cli go bu

May 10, 2022

Recursively searches a map[string]interface{} structure for another map[string]interface{} structure

msirecurse Recursively searches a map[string]interface{} structure for existence of a map[string]interface{} structure Motivation I wrote this package

Mar 3, 2022

Inflection is a string transformation library. It transforms strings from CamelCase to underscored string.

Inflection Inflection is a string transformation library. It transforms strings from CamelCase to underscored string. This is an implement of Inflecti

Jul 25, 2022

Package strnaming is used to Convert string to camelCase, snake_case, kebab-case.

strnaming Package strnaming is used to Convert string to camelCase, snake_case, kebab-case. Contents strnaming Contents API Examples Install Quick sta

Oct 24, 2021

Convert JSON string to Graphql

Convert JSON in string type (example below) to GraphQL Input in GolangConvert JSON in string type (example below) to GraphQL Input in Golang

Oct 5, 2021

Read data from rss, convert in pdf and send to kindle. Amazon automatically convert them in azw3.

Kindle-RSS-PDF-AZW3 The Kindle RSS PDF AZW3 is a personal project. The Kindle RSS PDF AZW3 is a personal project. I received a Kindle for Christmas, a

Jan 10, 2022

Golang string comparison and edit distance algorithms library, featuring : Levenshtein, LCS, Hamming, Damerau levenshtein (OSA and Adjacent transpositions algorithms), Jaro-Winkler, Cosine, etc...

Go-edlib : Edit distance and string comparison library Golang string comparison and edit distance algorithms library featuring : Levenshtein, LCS, Ham

Dec 20, 2022

An in-memory string-interface{} map with various expiration options for golang

TTLCache - an in-memory cache with expiration TTLCache is a simple key/value cache in golang with the following functions: Expiration of items based o

Jan 8, 2023

:triangular_ruler: Create beautiful generative image patterns from a string in golang.

:triangular_ruler: Create beautiful generative image patterns from a string in golang.

geopattern Create beautiful generative image patterns from a string in golang. Go port of Jason Long's awesome GeoPattern library. Read geopattern's d

Dec 29, 2022

Golang string comparison and edit distance algorithms library, featuring : Levenshtein, LCS, Hamming, Damerau levenshtein (OSA and Adjacent transpositions algorithms), Jaro-Winkler, Cosine, etc...

Go-edlib : Edit distance and string comparison library Golang string comparison and edit distance algorithms library featuring : Levenshtein, LCS, Ham

Dec 20, 2022

String-matching in Golang using the Knuth–Morris–Pratt algorithm (KMP)

gokmp String-matching in Golang using the Knuth–Morris–Pratt algorithm (KMP). Disclaimer This library was written as part of my Master's Thesis and sh

Dec 8, 2022
Comments
  • Proposal: Add String function that prints out days and weeks

    Proposal: Add String function that prints out days and weeks

    This is the current situation:

    t, _ := str2duration.ParseDuration("2w")
    fmt.Println(t.String()) // 672h0m0s
    

    It would be nice to have str2duration.String(t time.Duration) string:

    t, _ := str2duration.ParseDuration("2w")
    fmt.Println(str2duration.String(t)) // 2w
    

    Or to align with Go's output format (but that looks rather ugly):

    t, _ := str2duration.ParseDuration("2w")
    fmt.Println(str2duration.String(t)) // 2w0d0h0m0s
    
Copy of stdlib's time.Duration, but ParseDuration accepts other bigger units such as days, weeks, months and years

duration Copy of stdlib's time.Duration, but ParseDuration accepts other units as well: d: days (7 * 24 * time.Hour) w: weeks (7 * Day) mo: months (30

Jun 21, 2022
Carbon for Golang, an extension for Time

Carbon A simple extension for Time based on PHP's Carbon library. Features: Time is embedded into Carbon (provides access to all of Time's functionali

Dec 20, 2022
GoLang Parse many date strings without knowing format in advance.

Go Date Parser Parse many date strings without knowing format in advance. Uses a scanner to read bytes and use a state machine to find format. Much fa

Dec 31, 2022
:clock1: Date and Time - Golang Formatting Library
:clock1: Date and Time - Golang Formatting Library

Kair Date and Time - Golang Formatting Library Setup To get Kair > Go CLI go get github.com/GuilhermeCaruso/kair > Go DEP dep ensure -add github.com/G

Sep 26, 2022
Now is a time toolkit for golang

Now Now is a time toolkit for golang Install go get -u github.com/jinzhu/now Usage Calculating time based on current time import "github.com/jinzhu/n

Dec 23, 2022
Golang package to manipulate time intervals.

timespan timespan is a Go library for interacting with intervals of time, defined as a start time and a duration. Documentation API Installation Insta

Sep 26, 2022
timeutil - useful extensions (Timedelta, Strftime, ...) to the golang's time package

timeutil - useful extensions to the golang's time package timeutil provides useful extensions (Timedelta, Strftime, ...) to the golang's time package.

Dec 22, 2022
A simple, semantic and developer-friendly golang package for datetime

Carbon 中文 | English carbon 是一个轻量级、语义化、对开发者友好的 Golang 时间处理库,支持链式调用和 gorm、xorm、zorm 等主流 orm。 如果您觉得不错,请给个 star 吧 github:github.com/golang-module/carbon g

Jan 9, 2023
time format golang

a simple plugin to change date and time format

Sep 29, 2021
Go-olson-timezone - A Golang library that tries to figure out your local timezone

go-olson-timezone A Golang library that tries to figure out your local timezone.

Feb 16, 2022