github.com/simpleiot/simpleiot@v0.18.3/system/timezone.go (about)

     1  package system
     2  
     3  import (
     4  	"os"
     5  	"path"
     6  	"regexp"
     7  )
     8  
     9  // ReadTimezones returns a list of possible time zones
    10  // from the system
    11  // Possible arguments for zoneInfoDir:
    12  //
    13  //	"" (root dir)
    14  //	"US"
    15  //	"posix/America"
    16  func ReadTimezones(zoneInfoDir string) (listZones []string, err error) {
    17  
    18  	fileInfo, err := os.ReadDir(path.Join(zoneInfoPath, zoneInfoDir))
    19  	if err != nil {
    20  		return nil, err
    21  	}
    22  
    23  	for _, fi := range fileInfo {
    24  		if !fi.IsDir() { // if file, not directory
    25  			listZones = append(listZones, fi.Name())
    26  		}
    27  	}
    28  
    29  	return listZones, nil
    30  }
    31  
    32  // GetTimezone returns the current system timezone and
    33  // its path after zoneInfoPath
    34  func GetTimezone() (zoneInfoDir, zone string, err error) {
    35  
    36  	link, err := os.Readlink(zoneLink)
    37  	if err != nil {
    38  		return "", "", err
    39  	}
    40  
    41  	// extract the timezone and the zoneInfoDir from the full path
    42  	pattern := regexp.MustCompile(`/usr/share/zoneinfo/(.+)`)
    43  	matches := pattern.FindStringSubmatch(link)
    44  
    45  	if len(matches) < 2 {
    46  		return "", "", nil
    47  	}
    48  
    49  	pattern2 := regexp.MustCompile(`(.+)/(.+)`)
    50  	matches2 := pattern2.FindStringSubmatch(matches[1])
    51  
    52  	if len(matches2) < 3 {
    53  		return "", matches[1], nil
    54  	}
    55  
    56  	return matches2[1], matches2[2], nil
    57  }
    58  
    59  // SetTimezone sets the current system time zone
    60  func SetTimezone(zoneInfoDir, zone string) (err error) {
    61  
    62  	if _, err := os.Lstat(zoneLink); err == nil {
    63  		err := os.Remove(zoneLink)
    64  		if err != nil {
    65  			return err
    66  		}
    67  	}
    68  
    69  	err = os.Symlink(path.Join(zoneInfoPath, zoneInfoDir, zone), zoneLink)
    70  	if err != nil {
    71  		return err
    72  	}
    73  
    74  	return nil
    75  }
    76  
    77  // Path to zoneinfo
    78  const zoneInfoPath = "/usr/share/zoneinfo/"
    79  
    80  // Symbolic link for the system timezone
    81  const zoneLink = "/etc/localtime"