Golang program to print date and time according to the specified location

Here, we are going to learn how to print date and time according to the specified location in Golang (Go Language)?
Submitted by Nidhi, on March 23, 2021 [Last updated : March 04, 2023]

Printing the date and time according to the specified location in Golang

Problem Solution:

In this program, we will get the date and time of the specified location using the LoadLocation() and In() function and print the result on the console screen.

Program/Source Code:

The source code to print the date and time according to the specified location is given below. The given program is compiled and executed successfully.

Golang code to print the date and time according to the specified location

// Golang program to print date and time
// according to the specified location

package main

import "fmt"
import "time"

func main() {
	loc, error := time.LoadLocation("America/Los_Angeles")
	if error != nil {
		fmt.Println("Unable to load location")
	}

	ttime := time.Now()
	fmt.Println(ttime.In(loc))
}

Output:

2021-03-22 22:54:35.145256942 -0700 PDT

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 and time packages to use time and fmt related functions.

In the main() function, we loaded location "America/Los_Angeles" using LoadLocation() function. Then get the current date and time using the Now() function. After that, we printed the current date-time of "Los Angeles" using In() function on the console screen.

Golang Date & Time Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.