C++获取当前时间(VSCode+minGW)

目录

说明

代码

输出结果

参考


说明

使用vs code配置了minGW-w64

 使用了两种方法获取时间:

  1. 第一种是C的time,只能显示到秒,输出也要自己进行处理(要输出真实的日期,需要tm_year+1900, tm_mon+1)
  2. 第二种使用STL,显示到更小的位数(不足之处是没有好的时间格式化方法,不能方便的输出,所以一般是先转为time_t,C的方式来输出)
  3. 注意加入相应的头文件

代码

//共用
#include<iostream>
#include<string>
//getTimeOne()
#include<time.h> 
#include <sstream>
//getTimeTwo()
#include<chrono>
 
using namespace std;

void getTimeOne();
void getTimeTwo();

int main()
{
	getTimeOne();
	getTimeTwo();

    return 0;
}

void getTimeOne()
{	
	time_t now1 = time(NULL);
	tm* tm_t = localtime(&now1);
	stringstream ss;
    ss<< tm_t->tm_year + 1900 << ((tm_t->tm_mon + 1)>9?"-":"-0") << tm_t->tm_mon + 1 << ((tm_t->tm_mday)>9?"-":"-0") << tm_t->tm_mday
		<<((tm_t->tm_hour)>9?" ":" 0")<< tm_t->tm_hour << ((tm_t->tm_min)>9?":":":0")<< tm_t->tm_min << (( tm_t->tm_sec)>9?":":":0") << tm_t->tm_sec;
    cout << ss.str()<<endl;
}

void getTimeTwo()
{
	auto now = chrono::system_clock::now();
	//通过不同精度获取相差的毫秒数
	uint64_t dis_millseconds = chrono::duration_cast<chrono::milliseconds>(now.time_since_epoch()).count()
		- chrono::duration_cast<chrono::seconds>(now.time_since_epoch()).count() * 1000;
	time_t tt = chrono::system_clock::to_time_t(now);
	auto time_tm = localtime(&tt);
	char strTime[25] = { 0 };
	sprintf(strTime, "%d-%02d-%02d %02d:%02d:%02d %03d", time_tm->tm_year + 1900,
		time_tm->tm_mon + 1, time_tm->tm_mday, time_tm->tm_hour,
		time_tm->tm_min, time_tm->tm_sec, (int)dis_millseconds);
	cout << strTime << endl;
	
	//char* 转化为string类型
	// string time = (string)strTime;
}

输出结果

参考

  1. (1条消息) C++获取当前时间 (std::chrono)_最爱吹吹风-CSDN博客_std 当前时间
  2. C++11 std::chrono库详解 - mjwk - 博客园 (cnblogs.com)
  3. 无补充


版权声明:本文为weixin_42292586原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。