Open In App

time.String() Function in Golang With Examples

Improve
Improve
Like Article
Like
Save
Share
Report

In Go language, time packages supplies functionality for determining as well as viewing time. The String() function in Go language is used to find a string that represents the duration formats as “24h6m0.7s”. Here, the foremost zero units are deleted. And the stated duration with less than one-second format will use a smaller unit, for example, milli-, micro-, or nanoseconds, in order to make sure that the foremost digit is non-zero. The duration zero formats as 0s. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.

Syntax:

func (d Duration) String() string

Here, d is the duration of time.

Return value: It returns the string that represents the duration formats as 3h4m0.3s.

Example 1:




// Golang program to illustrate the usage of
// time.String() function
  
// Including main package
package main
  
// Importing fmt and time
import (
    "fmt"
    "time"
)
  
// Calling main
func main() {
  
    // Defining duration
    // of String method
    str, _ := time.ParseDuration("3h")
  
    // Prints string that
    // represents duration
    fmt.Printf(str.String())
}


Output:

3h0m0s

Example 2:




// Golang program to illustrate the usage of
// time.String() function
  
// Including main package
package main
  
// Importing fmt and time
import (
    "fmt"
    "time"
)
  
// Calling main
func main() {
  
    // Defining duration 
    // of String method
    time1 := time.Date(2019, time.October, 
                 23, 0, 0, 0, 0, time.UTC)
      
    time2 := time.Date(2020, time.April,
                3, 0, 0, 0, 0, time.UTC)
  
    // Prints the duration of time stated
    fmt.Println(time2.Sub(time1).String())
}


Output:

3912h0m0s

Here, the duration of time between time1 and time2 is returned in the form of string.



Last Updated : 21 Apr, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads