golang 调用win32api 对windows系统时间进行调用,主要参考的是微软的win32api文档,具体描述可以查看地址:
// 根据官方文档中的描述,GetLocalTime需要传一个输出参数,该参数是一个名为SYSTEMTIME的指针结构体 void GetLocalTime( [out] LPSYSTEMTIME lpSystemTime ); // SYSTEMTIME 定义: typedef struct _SYSTEMTIME { WORD wYear; WORD wMonth; WORD wDayOfWeek; WORD wDay; WORD wHour; WORD wMinute; WORD wSecond; WORD wMilliseconds; } SYSTEMTIME, *PSYSTEMTIME, *LPSYSTEMTIME; // word 类型在golang 里面可以看作是 uint16
具体的golang 代码如下:
var kernel32 = syscall.NewLazyDLL("kernel32.dll")
type SYSTEMTIME struct {
WYear uint16
WMonth uint16
WDayOfWeek uint16
WDay uint16
WHour uint16
WMinute uint16
WSecond uint16
WMilliseconds uint16
}
func gettime() string {
s := SYSTEMTIME{}
proc := kernel32.NewProc("GetLocalTime")
r, _, err := proc.Call(uintptr(unsafe.Pointer(&s)))
if r != 1 {
fmt.Println(err)
return time.Now().Format("2006/01/02 15:03:04")
}
// 格式化输出
formatlst := [6]string{"%d/", "%d/", "%d ", "%d:", "%d:", "%d"}
if s.WMonth <= 9 {
formatlst[1] = "0%d/"
}
if s.WDay <= 9 {
formatlst[2] = "0%d "
}
if s.WHour <= 9 {
formatlst[3] = "0%d:"
}
if s.WMinute <= 9 {
formatlst[4] = "0%d:"
}
if s.WSecond <= 9 {
formatlst[5] = "0%d"
}
var buffer bytes.Buffer
for i := 0; i < 6; i++ {
buffer.WriteString(formatlst[i])
}
return fmt.Sprintf(buffer.String(), s.WYear, s.WMonth, s.WDay, s.WHour, s.WMinute, s.WSecond)
}
func main() {
t := time.NewTicker(time.Second)
for {
select {
case <-t.C:
fmt.Println("now time", gettime())
}
}
}