Open In App
Related Articles

Getting the current date and time with timestamp in local and other timezones in Golang

Improve Article
Improve
Save Article
Save
Like Article
Like

We can get the current date and time with a timestamp in local with the help of Location() function and other timezones in Golang with the help of LoadLocation() function. The LoadLocation() takes a string(city name) as parameter and returns the place.
.location() takes no parameter and return location .time.now() returns current date and time with a timestamp in local.

1. location(): It takes no parameter and returns local time.

2. func LoadLocation(name string) (*Location, error): It takes the place name as a parameter. Returns the location with the given name or return nil as an error.

3. time.Now() : It return current time.

Example 1:




package main
  
import (
    "fmt"
    "time"
)
  
//main function
func main() {
  
    // with the help of time.Now()
    // store the local time
    t := time.Now()
      
    // print location and local time
    fmt.Println("Location : ", t.Location(), " Time : ", t)
}

Output:

Location :  Local  Time :  2009-11-10 23:00:00 +0000 UTC m=+0.000000001

Example 2:




package main
  
import (
    "fmt"
    "time"
)
  
// main function
func main() {
  
    // with the help of time.Now() 
    // store the local time
    t := time.Now()
      
    // print location and local time
    location, err := time.LoadLocation("America/New_York")
    if err != nil {
        fmt.Println(err)
    }
      
    // America/New_York
    fmt.Println("Location : ", location, " Time : ", t.In(location)) 
}

Output:

Location :  America/New_York  Time :  2009-11-10 18:00:00 -0500 EST

Last Updated : 22 Jun, 2020
Like Article
Save Article
Similar Reads
Related Tutorials