Open In App

time.Parse() 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 Parse() function in Go language is used to parse a formatted string and then finds the time value that it forms. Moreover, this function is defined under the time package. Here, you need to import “time” package in order to use these functions.

Syntax:

func Parse(layout, value string) (Time, error)

Here, layout specifies the format by displaying in what way the reference time, that is defined as Mon Jan 2 15:04:05 -0700 MST 2006 would be explained if it were the value. However, the previously defined layouts like UnixDate, ANSIC, RFC3339 etc, explain standard as well as suitable representations of the reference time. And the value parameter holds string. Where, the elements that are removed from the value are presumed to be zero and when zero is not possible then its assumed to be one.

Return Value: It returns the time value that it represents. And if a time zone indicator is not present then it returns a time in UTC.

Example 1:




// Golang program to illustrate the usage of
// time.Parse() function
  
// Including main package
package main
  
// Importing fmt and time
import "fmt"
import "time"
  
// Calling main
func main() {
  
    // Declaring layout constant
    const layout = "Jan 2, 2006 at 3:04pm (MST)"
  
    // Calling Parse() method with its parameters
    tm, _ := time.Parse(layout, "Feb 4, 2014 at 6:05pm (PST)")
  
    // Returns output
    fmt.Println(tm)
}


Output:

2014-02-04 18:05:00 +0000 PST

Here, the output returned is in PST as defined above and the layout constant and value used here are long-form of it.

Example 2:




// Golang program to illustrate the usage of
// time.Parse() function
  
// Including main package
package main
  
// Importing fmt and time
import "fmt"
import "time"
  
// Calling main
func main() {
  
    // Declaring layout constant
    const layout = "2006-Jan-02"
  
    // Calling Parse() method with its parameters
    tm, _ := time.Parse(layout, "2014-Feb-04")
  
    // Returns output
    fmt.Println(tm)
}


Output:

2014-02-04 00:00:00 +0000 UTC

Here, the output returned is in UTC as there is no time zone indicator and the layout constant and value used here are short form of it.



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