Golang program to convert the local time to GMT


In this article, we will learn to write a Go language program to convert the local time to GMT using internal functions like Now() Time, LoadLocation()and time.In(). Local time is the time of a particular region which is calculated using position of the sun at noon.

The local time is obtained using Now function from the time package whereas the local time is converted to GMT using ln function from the time package.

Syntax

func Now() Time

The Now() function is defined in time package. This function generates the current local time.To use this function, we have to first import the time package in our program.

time.LoadLocation()

This function belongs to the time package and it loads the location by its name. For ex-local which it will take as an argument.

time.ln()

This function is the part of the time package. It is used to return a copy of the time value with the different time zone.

Algorithm

  • Step 1 − Import the required packages in the program

  • Step 2 − Create a main function

  • Step 3 − In the main find the local time and the GMT time using internal functions

  • Step 4 − Print the local time and GMT time on the console using Println function from fmt package

Example 1

In this example, we will write a Go language program to convert local time to GMT using local in LoadLocation function. The location obtained will be passed in the ln method to get the GMT time.

package main

import (
   "fmt"
   "time"
)

func main() {
   local_time := time.Now()   
   fmt.Println("Local Time:", local_time)

   location, err := time.LoadLocation("Local")  
   if err != nil {
      panic(err)
   }

   gmt_time := local_time.In(location).UTC()
   fmt.Println("GMT Time:", gmt_time)  
}

Output

Local Time: 2023-04-03 04:02:17.266341285 +0000 UTC m=+0.000012865
GMT Time: 2023-04-03 04:02:17.266341285 +0000 UTC

Example 2

In this example, we will write a Go language program to convert the local time to GMT using GMT in LoadLocation method. The GMT location will be passed in ln to get GMT time.

package main

import (
    "fmt"
    "time"
)

func main() {
    local_time := time.Now()

    gmt_location := time.FixedZone("GMT", 0)

    gmt_time := local_time.In(gmt_location)

    fmt.Println("Local Time:", local_time)
    fmt.Println("GMT Time:", gmt_time)
}

Output

Local Time: 2023-04-03 04:03:14.220027913 +0000 UTC m=+0.000016862
panic: unknown time zone GMT

Conclusion

We executed the program of converting the local time to GMT using two examples. In the first example, we loaded the local location and in the second example we loaded the GMT location, then in both the examples we used ln function to convert the local time to GMT.

Updated on: 04-Apr-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements