VC中得到当前系统的时间和日期

本文介绍了三种在程序中获取当前时间的方法:使用CRT函数、SYSTEMTIME和CTime类。这些方法可以将时间转换为年月日时分秒的格式,适用于需要记录精确时间的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

得到时间的方法一般都是得到从1900年0点0分到现在的秒数,然后转为年月日时分秒的形式得到当前的时间(时分秒)。主要方法如下:
1)使用CRT函数

char szCurrentDateTime[32];
time_t nowtime;
struct tm* ptm;
time(&nowtime);
ptm = localtime(&nowtime);
sprintf(szCurrentDateTime, "%4d-%.2d-%.2d %.2d:%.2d:%.2d",
ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday,
ptm->tm_hour, ptm->tm_min, ptm->tm_sec);


2)使用SYSTEMTIME

char szCurrentDateTime[32];
SYSTEMTIME systm;
GetLocalTime(&systm);
sprintf(szCurrentDateTime, "%4d-%.2d-%.2d %.2d:%.2d:%.2d",
systm.wYear, systm.wMonth, systm.wDay,
systm.wHour, systm.wMinute, systm.wSecond);


3)使用CTime

char szCurrentDateTime[32];
CTime nowtime;
nowtime = CTime::GetCurrentTime();

sprintf(szCurrentDateTime, "%4d-%.2d-%.2d %.2d:%.2d:%.2d",
nowtime.GetYear(), nowtime.GetMonth(), nowtime.GetDay(),
nowtime.GetHour(), nowtime.GetMinute(), nowtime.GetSecond());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值