c++ 获取当前时间--年月日、时分秒、毫秒

 

方法一:

精确到秒

#include <iostream>
#include <string>
#include <time.h>
#pragma warning(disable:4996)



struct NowDate
{
	char tmp0[16]; //年月日
	char tmp1[16]; //时分秒
	char tmp2[32]; //年月日时分秒
};

NowDate getTime()
{
	time_t timep;
	time(&timep);
	NowDate date;

	strftime(date.tmp0, sizeof(date.tmp0), "%Y_%m_%d", localtime(&timep));
	strftime(date.tmp1, sizeof(date.tmp1), "%H_%M_%S", localtime(&timep));
	strftime(date.tmp2, sizeof(date.tmp2), "%Y%m%d%H%M%S", localtime(&timep));

	return date;
}


int main()
{
	NowDate current_time = getTime();
	std::string year_mom_day = current_time.tmp0;
	std::string hour_mim_sec = current_time.tmp1;
	std::string year_mom_day_hour_mim_sec = current_time.tmp2;
	std::cout << year_mom_day << std::endl;
	std::cout << hour_mim_sec << std::endl;
	std::cout << year_mom_day_hour_mim_sec << std::endl;
	//std::cout << year_mom_day << std::endl;


	system("pause");
}

 

方法二:

精确到毫秒

#include <iostream>
#include <windows.h>

using namespace std;


std::vector<string> get_current_time()
{
	/*能精确到毫秒*/
	/*
	#include <windows.h>
	#include <iostream>
	*/
	SYSTEMTIME st = { 0 };
	GetLocalTime(&st);  //获取当前时间 可精确到ms

	char tmpbuff[16];
	/*年*/
	sprintf(tmpbuff, "%d", st.wYear);
	std::string year = tmpbuff;
	/*月*/
	sprintf(tmpbuff, "%d", st.wMonth);
	std::string month = tmpbuff;
	/*日*/
	sprintf(tmpbuff, "%d", st.wDay);
	std::string day = tmpbuff;
	/*时*/
	sprintf(tmpbuff, "%d", st.wHour);
	std::string hour = tmpbuff;
	/*分*/
	sprintf(tmpbuff, "%d", st.wMinute);
	std::string minute = tmpbuff;
	/*秒*/
	sprintf(tmpbuff, "%d", st.wSecond);
	std::string second = tmpbuff;
	/*毫秒*/
	sprintf(tmpbuff, "%d", st.wMilliseconds);
	std::string millisecond = tmpbuff;

	std::vector<string>current_time = {};

	current_time.push_back(year + month + day);
	current_time.push_back(hour + minute + second);
	current_time.push_back(year + month + day + hour + minute + second);
	current_time.push_back(year + month + day + hour + minute + second + "_" + millisecond + "ms");

	return current_time;
}


int main()
{
	std::vector<string>current_time = get_current_time();
	std::string year_mom_day = current_time[0];
	std::string hour_mim_sec = current_time[1];
	std::string year_mom_day_hour_mim_sec = current_time[2];
	std::string year_mom_day_hour_mim_sec_millsec = current_time[3];

	cout << year_mom_day << endl;
	cout << hour_mim_sec << endl;
	cout << year_mom_day_hour_mim_sec << endl;
	cout << year_mom_day_hour_mim_sec_millsec << endl;
    
}



 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

枫呱呱

如果这篇博文对你有用,求打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值