How to convert a string to a time in Golang

Key takeaways:

  • The time.Parse() function in Golang is essential for converting a string into a time object.

  • The function requires two parameters: a format string that specifies the expected date format and the actual date string to be converted.

  • Golang provides predefined time formats like RFC1123, which can be used for parsing strings in standard formats.

In programming, working with time and dates is a fundamental task, especially in applications that require event scheduling, logging, or time-based operations. One common challenge that developers face is converting a time represented as a string into a time object, which allows more advanced manipulations. In Golang, this conversion is straightforward but requires a solid understanding of how time formatting works.

In this Answer, we will learn how to properly convert a string to time.

The time.Parse() function

Golang provides the time.Parse() function in the time package to convert a string into a time value. This function is essential for handling time-related data received in string format from sources like user input, APIs, or databases.

Syntax

time.Parse(format, dateString)

Parameters

The Parse function accepts the following parameters:

  • format: The format in which the time (output) should be. For example DD-MM-YYYY.
  • dateString: The string that needs to be converted to time.

Return value

The Parse function will return a Golang time object.

Golang code to convert a string to a time

In the following code, we will convert a string to time using the Parse function:

package main
import (
"fmt"
"time"
)
func main() {
dateString := "2021-11-22"
date, error := time.Parse("2006-01-02", dateString)
if error != nil {
fmt.Println(error)
return
}
fmt.Printf("Type of dateString: %T\n", dateString)
fmt.Printf("Type of date: %T\n", date)
fmt.Println()
fmt.Printf("Value of dateString: %v\n", dateString)
fmt.Printf("Value of date: %v", date)
}

Explanation

  • Lines 3–6: we have imported the necessary packages.

  • Line 8: Inside the main() function, we have declared a string dateString and initialized it with 2021-11-22 in line 9.

  • Line 10: we then converted the string to date using the time.Parse() function by passing two parameters; the format and the dateString.

  • Line 13: If a conversion error occurs, we output it on the console.

  • Lines 17–21: If there are no errors, we output the type and value of dateString and date respectively on the console.

Predefined time format with time.Parse() function

We can use multiple predefined format constants e.g., RFC1123"Mon, 02 Mar 2004 15:04:05 MST", ANSIC"Mon Feb _2 15:04:05 2008", and so on. Let’s try out another example where we utilize the RFC1123 format constant for date and time representation.

package main
import (
"fmt"
"time"
)
func main() {
// using layout RFC1123
parseTime, err := time.Parse(time.RFC1123, "Sun, 12 Dec 2021 12:23:00 UTC")
if err != nil {
panic(err)
}
fmt.Printf("The Parsed time is: %v\n", parseTime)
fmt.Printf("The Formatted Parsed time is: %v", parseTime.Format("02, Jan 2006"))
}
  • Line 10: parses the second argument using the RFC1123 layout and saves the corresponding time object to variable parseTime.

  • Line 15: formats the parsed date and time value using the layout specified by the Format() method and prints the result to the standard output

Conclusion

In conclusion, converting strings to time objects in Go is an essential skill for handling dates and times in the applications. Using functions like time.Parse(), we can easily manage time data and account for different time zones. Mastering these techniques ensures the code runs reliably and efficiently across various locales.

Want to learn Go and unlock its full potential? The Way to Go course is your perfect starting point! This course will teach you Go's core constructs and advanced concepts like error-handling, networking, and templating and help you master efficient programming techniques. With hands-on projects and real-world examples, you’ll gain the skills to build robust, concurrent applications.

Start your journey to mastering Go today!

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How to convert a string to number in Golang


Can I use predefined time constants like RFC1123 with time.Parse()?

Yes, we can use predefined time constants like RFC1123 with time.Parse() in Golang


How do I handle leap years when parsing time in Golang?

In Golang, handling leap years when parsing time typically involves ensuring the correct date format and accounting for the fact that February has 29 days in leap years. The time.Parse() function in Golang will correctly handle leap years as long as the string you are parsing represents a valid date.


Free Resources