Golang : ISO8601 Duration Parser example
An example on how to parse ISO-8601 duration in string format and convert it to time.Duration
type. However, this example doesn't parse M (month) because it cannot determine if the month is 29/30 or 31 days.
Here you go!
package main
import (
"fmt"
duration "github.com/channelmeter/iso8601duration"
)
func main() {
// note : doesn't support month!
// some months have 30 days and some 31/29 days!
dura, err := duration.FromString("P1Y2DT3H4M5S") // dura is time.Duration type
if err != nil {
fmt.Println("Error : ", err)
}
fmt.Println("Duration : ", dura)
fmt.Println("Year : ", dura.Years)
fmt.Println("Day : ", dura.Days)
fmt.Println("Hours : ", dura.Hours)
fmt.Println("Minutes : ", dura.Minutes)
fmt.Println("Seconds : ", dura.Seconds)
fmt.Println("Weeks : ", dura.Weeks)
fmt.Println("To duration : ", dura.ToDuration())
fmt.Println("Has Time Part? : ", dura.HasTimePart())
}
Sample output :
Year : 1
Day : 2
Hours : 3
Minutes : 4
Seconds : 5
Weeks : 0
To duration : 8811h4m5s
Has Time Part? : true
References :
https://github.com/ChannelMeter/iso8601duration
https://en.wikipedia.org/wiki/ISO_8601?oldformat=true#Durations
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.3k Golang : Detect face in uploaded photo like GPlus
+11.8k Golang : Convert(cast) bigint to string
+13.3k Golang : Read from buffered reader until specific number of bytes
+20.2k Swift : Convert (cast) Int to int32 or Uint32
+5.6k Unix/Linux/MacOSx : Get local IP address
+9.9k Golang : Convert octal value to string to deal with leading zero problem
+13.5k Golang : reCAPTCHA example
+12.1k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+29.9k Golang : Get time.Duration in year, month, week or day
+7.1k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+8.4k Golang : How to check if input string is a word?
+12.3k Golang : 2 dimensional array example