golang-windows通过win32api获取本地系统时间

本文介绍了如何在Golang中通过调用Windows的kernel32.dll库的GetLocalTime函数来获取当前系统时间,并展示了具体的代码实现。通过定义SYSTEMTIME结构体并处理返回值,实现了时间的格式化输出。
摘要由CSDN通过智能技术生成

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())
		}
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值