【C++】获取当前时间的两种方式

  • Post author:
  • Post category:其他


下面是我查资料找到的我认为好用的两种方式,区别在于对localtime(&t)函数返回值的处理上。

我做成了getYear()和getMonth()函数,方便自己随时调用。


方法一:利用strftime()函数


strftime( ) 函数说明参考:https://blog.csdn.net/SanQi_Abao/article/details/94964665

可以获取的时间种类很多,这里只实现部分。

#include <iostream>
#include <cstdio>
#include <cmath>

using namespace std;

static string getYear() {
	time_t t = time(NULL);
	char ch[6] = { 0 };
	strftime(ch, sizeof(ch) - 1, "%Y", localtime(&t));
	return ch;
}
static string getMonth() {
	time_t t = time(NULL);
	char ch[4] = { 0 };
	strftime(ch, sizeof(ch) - 1, "%m", localtime(&t));
	return ch;
}
static string getDay() {
	time_t t = time(NULL);
	char ch[4] = { };
	strftime(ch, sizeof(ch) - 1, "%d", localtime(&t));
	return ch;
}
static string getHour() {
	time_t t = time(NULL);
	char ch[4] = { 0 };
	strftime(ch, sizeof(ch) - 1, "%H", localtime(&t));
	return ch;
}
static string getMinute() {
	time_t t = time(NULL);
	char ch[4] = { 0 };
	strftime(ch, sizeof(ch) - 1, "%M", localtime(&t));
	return ch;
}
static string getSecond() {
	time_t t = time(NULL);
	char ch[4] = { 0 };
	strftime(ch, sizeof(ch) - 1, "%S", localtime(&t));
	return ch;
}

int main() {
	cout << "year=" << getYear() << endl;
	cout << "month=" << getMonth() << endl;
	cout << "day=" << getDay() << endl;
	cout << "hour=" << getHour() << endl;
	cout << "minute=" << getMinute() << endl;
	cout << "second=" << getSecond() << endl;
	return 0;
}

在这里插入图片描述


方法二:利用结构体tm

//结构体tm内的成员
  int tm_sec;			/* Seconds.	[0-60] (1 leap second) */
  int tm_min;			/* Minutes.	[0-59] */
  int tm_hour;			/* Hours.	[0-23] */
  int tm_mday;			/* Day.		[1-31] */
  int tm_mon;			/* Month.	[0-11] */
  int tm_year;			/* Year	- 1900.  */
  int tm_wday;			/* Day of week.	[0-6] */
  int tm_yday;			/* Days in year.[0-365]	*/
  int tm_isdst;			/* DST.		[-1/0/1]*/
//看结构体成员就知道还能获取其他时间数据,我这里就不写全了
#include <iostream>
#include <cstdio>
#include <cmath>

using namespace std;

int getYear() {
	time_t t;
	time(&t);
	struct tm* tmp = localtime(&t);
	return tmp->tm_year + 1900;
}
int getMonth() {
	time_t t;
	time(&t);
	struct tm* tmp = localtime(&t);
	return tmp->tm_mon + 1;
}
int getDay() {
	time_t t;
	time(&t);
	struct tm* tmp = localtime(&t);
	return tmp->tm_mday;
}
int getHour() {
	time_t t;
	time(&t);
	struct tm* tmp = localtime(&t);
	return tmp->tm_hour;
}
int getMinute() {
	time_t t;
	time(&t);
	struct tm* tmp = localtime(&t);
	return tmp->tm_min;
}
int getSeond() {
	time_t t;
	time(&t);
	struct tm* tmp = localtime(&t);
	return tmp->tm_sec;
}


int main() {

	printf("year=%d, month=%d, day=%d, hour=%d, second=%d\n", getYear(),
			getMonth(), getDay(), getHour(), getSeond());
//year=2020, month=7, day=2, hour=9, second=3
}

========================================================

【文章为本人的学习笔记部分的分享,有任何错误地方欢迎评论指出,万分感谢!】



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