Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why running Golang's time.Now() at OpenWRT always get UTC time?

Tags:

go

openwrt

I wrote a Golang program that runs on OpenWRT.

package main

import (
    "fmt"
    "time"
)

func main(){
    fmt.Println(time.Now())
}

When I run this program on my Macbook, I always get the correct local time.

However, when running this program on OpenWRT, I always get UTC time.

I have set the time zone and time of OpenWRT. When I execute uci show system, I can see the right time zone. When I execute date the right local time can be display correctly.

So my question is, how do I get the correct local time using Golang's time.Now() on OpenWRT?

like image 222
Alan42 Avatar asked Oct 15 '25 15:10

Alan42


2 Answers

The root of my problem is that my OpenWRT lacks the zoneinfo package. So I run opkg update && opkg install zoneinfo-xxx first.

This is part of go/src/time/zoneinfo_unix.go:

func initLocal() {
    // consult $TZ to find the time zone to use.
    // no $TZ means use the system default /etc/localtime.
    // $TZ="" means use UTC.
    // $TZ="foo" means use /usr/share/zoneinfo/foo.

    ...

}

According to this file, if there is no "TZ" variable, Golang will use the time zone pointed to by /etc/localtime when calling time.Now().

Then I set time zone at /etc/config/system (option zonename 'xxxxxx') and run /etc/init.d/system restart. Finally, I can get the correct time.Now().

like image 157
Alan42 Avatar answered Oct 18 '25 06:10

Alan42


OpenWRT stores the time zone inside a file named /etc/TZ. If this file is missing or empty, OpenWRT assumes the local time equals UTC time. Source

how do I get the correct local time using Golang's time.Now() on OpenWRT?

Specifying the Time Zone with TZ

The is the value you must add to or substract from the local time to get the UTC time. This offset will be positive if the local time zone is west of the Prime Meridian and negative if it is east.

like image 38
Philidor Avatar answered Oct 18 '25 08:10

Philidor