获取时间 Windows API

时间是一个非常重要的信息,比如写LOG时,就需要把时间输出来,跟踪程序是什么时候出错的。或者当你开发一个银行交易系统时,就要记录当前交易的时间,以便后面可以输出报表,打印给信用卡用户。根据不同的需求,可能需要使用不同的时间,目前有UTC( Coordinated Universal Time)和本地时间。UTC是格林威治时间,也就是全球标准时间。本地时间就是相对于UTC而言的,比如中国北京是在东8区,相对于UTC就多了8个小时。一般使用到的时间都是使用本地时间,也就是调用函数GetLocalTime。

获取UTC时间:

void GetSystemTime(
  LPSYSTEMTIME lpSystemTime
);

获取本地时间:

void GetLocalTime(
  LPSYSTEMTIME lpSystemTime
);

二者都是Windows API ,使用样例:

#include <stdio.h>
#include <stdlib.h>


//获取 秒级时间
#include <time.h>
inline void GetDate(char* pTimeBuf, unsigned int dwSize)
{
	if (pTimeBuf == NULL)
	{
		return;
	}
	time_t tTime = time(NULL); 
	struct tm* ptReflash = localtime(&tTime);
	strftime(pTimeBuf, dwSize, "%Y-%m-%d %H:%M:%S", ptReflash);
}

//获取 毫秒级时间
#include <Windows.h>
inline void Mc_GetLocalTime(char* pTimeBuf, unsigned int dwSize)
{
	if (pTimeBuf == NULL)
	{
		return;
	}
	SYSTEMTIME sys = {0}; 
	GetLocalTime( &sys ); 
	sprintf_s(pTimeBuf, dwSize,"%4d-%02d-%02d %02d:%02d:%02d.%03d",sys.wYear,sys.wMonth,sys.wDay,sys.wHour,sys.wMinute, sys.wSecond,sys.wMilliseconds);
}

//获取 毫秒级时间
inline void Mc_GetSystemTime(char* pTimeBuf, unsigned int dwSize)
{
	if (pTimeBuf == NULL)
	{
		return;
	}
	SYSTEMTIME sys = {0}; 
	GetSystemTime( &sys ); 
	sprintf_s(pTimeBuf, dwSize,"%4d-%02d-%02d %02d:%02d:%02d.%03d",sys.wYear,sys.wMonth,sys.wDay,sys.wHour,sys.wMinute, sys.wSecond,sys.wMilliseconds);
}


int main()
{
	// 本地时间
	char achTimeBuf[40] = {0};
	Mc_GetLocalTime(achTimeBuf, 40);
	printf("\n[GetLocalTime] %s\n", achTimeBuf);

	// UTC时间
	Mc_GetSystemTime(achTimeBuf, 40);
	printf("\n[GetSystemTime] %s\n", achTimeBuf);

	// 
	GetDate(achTimeBuf, 40);
	printf("\n[strftime] %s\n", achTimeBuf);

	system("pause");
	return 0;
}

结果:
在这里插入图片描述

注意

It is not recommended that you add and subtract values from the SYSTEMTIME structure to obtain relative times. Instead, you should

  • Convert the SYSTEMTIME structure to a FILETIME structure.
  • Copy the resulting FILETIME structure to a ULARGE_INTEGER structure.
  • Use normal 64-bit arithmetic on the ULARGE_INTEGER value.

The system can periodically refresh the time by synchronizing with a time source. Because the system time can be adjusted either forward or backward, do not compare system time readings to determine elapsed time. Instead, use one of the methods described in Windows Time.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值