一些用法一一获取时间的几种方法

我们经常需要获取当前时间,几种常用的方法介绍如下:

1.方式一:利用GetLocalTime()函数

#include <Windows.h>
#include <iostream>
#include <time.h>
using namespace std;

int main()
{
	SYSTEMTIME sTime;
	GetLocalTime(&sTime);

	char szTime[64]={0};
	sprintf_s(szTime,sizeof(szTime),"%04d/%02d/%02d %02d:%02d:%02d:%03d",sTime.wYear,sTime.wMonth,sTime.wDay,sTime.wHour,sTime.wMinute,sTime.wSecond,sTime.wMilliseconds);
	cout<<szTime<<endl;
	return 0;
}
2017/12/07 11:27:59:107
请按任意键继续. . .

2.方式二:利用localtime()函数

#include <iostream>
using namespace std;
#include <time.h>

int main()
{
	time_t t = time(NULL);
	struct tm* stime=localtime(&t);
	char szTime[64]={NULL};
	sprintf_s(szTime,sizeof(szTime),"%04d-%02d-%02d %02d:%02d:%02d",1900+stime->tm_year,1+stime->tm_mon,
		stime->tm_mday, stime->tm_hour,
		stime->tm_min,stime->tm_sec);
	cout<<szTime<<endl;
	return 0;
}
2017-12-07 11:30:25
请按任意键继续. . .
3.方式三:利用strftime格式化时间输出

#include <iostream>
using namespace std;
#include <time.h>

int main()
{
	time_t t = time(0); 
	char szTime[64]={NULL};
	strftime(szTime, sizeof(szTime), "%Y-%m-%d %H:%M:%S",localtime(&t)); 
	cout<<szTime<<endl;
	return 0;
}
2017-12-07 11:31:13
请按任意键继续. . .
4.方式四:利用ctime日历时间法输出

#include <iostream>
using namespace std;
#include <time.h>
#include <string>

int main()
{
	time_t tm;
	time(&tm);
	char szTime[64]={NULL};
	strcpy(szTime,ctime(&tm));
	//或者
	//struct  tm* stime=localtime(&tm);
	//strcpy(szTime,asctime(stime));
	cout<<szTime<<endl;
	return 0;
}
Thu Dec 07 11:32:21 2017

请按任意键继续. . .

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值