time.String() Function in Golang With Examples

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:



filter_none

edit
close

play_arrow

link
brightness_4
code

// 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())
}

chevron_right


Output:

3h0m0s

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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())
}

chevron_right


Output:

3912h0m0s

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




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.