Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
communitycreator

How to convert a string to a time in Golang

Shubham Singh Kshatriya

Overview

A string can be converted to a time in Golang using the Parse function within the time package.

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.

Example

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

  • In lines 3-6, we have imported the necessary packages.

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

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

  • If there occurs some error while conversion, we output it on the console (line 13).

  • If there are no errors, we output the type and value of dateString and date respectively on the console (line17-21).

RELATED TAGS

golang
communitycreator

CONTRIBUTOR

Shubham Singh Kshatriya
RELATED COURSES

View all Courses

Keep Exploring