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 👍

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

I'm working on some more Cheat Sheets book on Jquery, TypeScript, React js and for other languages. I will send it once it's completed.

Stay tuned working on React Js Cheat Sheets Book

Related Posts