windows获取时间方法

方法一:
用c语言库函数中的time函数、ctime函数和ctime_s()函数,精确到秒

time函数:
头文件:time.h
功能:获取当前的系统时间,返回一个time_t类型(即一个大整数)。
用法:time_t time(time_t * timer)

ctime函数:

头文件:time.h
功能:ctime功能是 把日期和时间转换为字符串

用法:char *ctime(const time_t *time);

ctime_s函数:(比ctime函数安全性更高)

头文件:time.h
功能:把日期和时间转换为字符串
用法:errno_t ctime_s(char* buffer, size_t numberOfElements, const time_t *time);

实际代码:
char time_str[26];
time_t current_time = time(0);
ctime_s(time_str, 26, &current_time);
print("The time is %s", time_str);

方法二:
用Windows API函数:GetLocalTime,精确到微秒
GetLocalTime函数:
头文件:winbase.h
链接库:coredll.lib
功能:用来获取当地的当前系统日期和时间
用法:VOID GetLocalTime(LPSYSTEMTIME lpSystemTime);

实际代码:
SYSTEMTIME st;
GetLocalTime(&st);
cout<<st.wYear<<":"<<st.wMonth<<":"<<st.wDay<<":"<<st.wHour<<":"<<st.wMinute<<":"<<st.wSecond<<":"<<st.wMilliseconds<<endl;


注:发现直接从小时输出会出错,从年份开始输出就不会,不知道为什么。

猜你喜欢

转载自blog.csdn.net/LYH66/article/details/14226211
今日推荐