Home »
Golang »
Golang Programs
Golang program to print individual elements of date and time using the inbuilt function
Here, we are going to learn how to print individual elements of date and time using the inbuilt function in Golang (Go Language)?
Submitted by Nidhi, on March 21, 2021 [Last updated : March 04, 2023]
How to print individual elements of date and time in Golang?
Problem Solution:
In this program, we will get the current date and time using time.Now() function. Then we get the elements of date and time using inbuilt functions.
Program/Source Code:
The source code to print individual elements of date and time using the inbuilt function is given below. The given program is compiled and executed successfully.
Golang code to print individual elements of date and time using the inbuilt function
// Golang program to print individual elements of date and
// time using the inbuilt function
package main
import "fmt"
import "time"
func main() {
//Get the current date and time.
currentDateTime := time.Now()
day := currentDateTime.Day()
month := currentDateTime.Month()
year := currentDateTime.Year()
hour := currentDateTime.Hour()
min := currentDateTime.Minute()
sec := currentDateTime.Second()
fmt.Printf("\nDay : %d", day)
fmt.Printf("\nMonth : %d", month)
fmt.Printf("\nYear : %d", year)
fmt.Printf("\nHour : %d", hour)
fmt.Printf("\nMinute : %d", min)
fmt.Printf("\nSecond : %d", sec)
}
Output:
Day : 21
Month : 3
Year : 2021
Hour : 6
Minute : 24
Second : 42
Explanation:
In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.
In the main() function, we called time.Now() to get the current date and time. After that, we get the individual elements of date and time using built-in functions and print the result on the console screen.
Golang Date & Time Programs »