c++ get current time string

code

void getNowTimePrefix(std::string& prefix)
{
    
    
	std::time_t nowTime;
	struct tm* p = new tm;
	std::time(&nowTime);
	localtime_s(p, &nowTime);
	int year = p->tm_year + 1900;
	int month = p->tm_mon + 1;
	int day = p->tm_mday;
	int hour = p->tm_hour;
	int minute = p->tm_min;
	int second = p->tm_sec;
	delete p;

	prefix = std::to_string(year)
		+ std::string(2 - std::to_string(month).length(), '0') + std::to_string(month)
		+ std::string(2 - std::to_string(day).length(), '0') + std::to_string(day)
		+ "_"
		+ std::string(2 - std::to_string(hour).length(), '0') + std::to_string(hour)
		+ std::string(2 - std::to_string(minute).length(), '0') + std::to_string(minute)
		+ std::string(2 - std::to_string(second).length(), '0') + std::to_string(second);
}

usage

#include<iostream>
using namespace std;

int main()
{
    
    
	std::string nowTimePrefix;
	getNowTimePrefix(nowTimePrefix);

	cout << nowTimePrefix << endl;

	return 0;
}

result

Insert image description here

Guess you like

Origin blog.csdn.net/sdhdsf132452/article/details/133240194