C++ converts the current system time into standard format time and timestamp

1: First convert the system time into a standard format time, and then into a timestamp.

#include "iostream"
#include "time.h"
#include "string.h"
using namespace std;
int main()
{
	time_t rawtime ; 
	struct tm * timeinfo; 
	char s[100];  
	time ( &rawtime ); 
	timeinfo = localtime ( &rawtime ); 
	time_t tick = mktime(timeinfo);
	strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", timeinfo); 
	printf("%d: %s\n", (int)tick, s);   
	int Year = timeinfo->tm_year+1900;
	int Mon = timeinfo->tm_mon+1;
	int Day = timeinfo->tm_mday;
	int Hour = timeinfo->tm_hour;
	int Min = timeinfo->tm_min;
	int Second = timeinfo->tm_sec;
	cout << Year << ":" << Mon << ":" << Day << "-" << Hour << ":" << Min << ":" << Second << endl;
	return 0;
}

 

among them:

int Year = timeinfo->tm_year+1900;
int Mon = timeinfo->tm_mon+1;

The hours, minutes, and seconds remain the same for the rest of the day.

 

The results of the operation are as follows:

 

2: First convert the system time into a timestamp, and then into a standard format time.

#include "iostream"
#include "time.h"
#include "string.h"
using namespace std;
int main()
{
	time_t now;                                                                                                                      
	int unixTime = (int)time(&now);
	time_t tick = (time_t)unixTime;  
	struct tm tm;   
	char s[100];  
	tm = *localtime(&tick);  
	strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", &tm);  
	printf("%d: %s\n", (int)unixTime, s);   
	return 0;
}

 

The results of the operation are as follows:

Thanks: https://gameinstitute.qq.com/community/detail/126521

Guess you like

Origin blog.csdn.net/xiaoshunzi111/article/details/90510128