How to get current time in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

Today, we will learn to get the current time in golang. here we will use the time package to get the current time, the fmt package to print in the golang console.

The time package provides the Now() method to get the current time, we will use this method and value in a variable, and after that, we will use the fmt.Println() method to print the current time.

Let’s start…

// Golang program to get the current time
package main
  
// Here "fmt" is formatted IO which
// is same as C’s printf and scanf.
import "fmt"
  
// importing time module
import "time"
  
// Main function
func main() {
  
    // Using time.Now() function.
    dt := time.Now()
    fmt.Println("Current date and time is: ", dt.String())
}

Well, when run the above code, you will get current date and time both.

print, current time, golang

Try it yourself

But if want to show only time, you have to format it like below example.

// Golang program to get the current time
package main
  
// Here "fmt" is formatted IO which
// is same as C’s printf and scanf.
import "fmt"
  
// importing time module
import "time"
  
// Main function
func main() {
    // Using time.Now() function.
    dt := time.Now()
    fmt.Println(dt.Format("15:04:05"))
  
}

print, current time formated, golang

Try it yourself

All the best 👍

Follow me on Twitter