C++ 日期和时间
C++ 标准库没有提供合适的日期类型。C++ 从 C 语言继承了用于日期和时间操作的结构体和函数。要访问与日期和时间相关的函数和结构,需要在 C++ 程序中包含 <ctime> 头文件。
有四种与时间相关的类型:clock_t, time_t, size_t 和 tm。这些类型——clock_t、size_t 和 time_t 能够以某种整数形式表示系统时间和日期。
结构体类型 tm 以 C 结构的形式保存日期和时间,包含以下元素:
struct tm {
int tm_sec; // 分钟内的秒数,从 0 到 61
int tm_min; // 小时内的分钟,从 0 到 59
int tm_hour; // 一天中的小时,从 0 到 24
int tm_mday; // 月份中的天,从 1 到 31
int tm_mon; // 年份中的月份,从 0 到 11
int tm_year; // 从 1900 年开始的年份
int tm_wday; // 从星期日开始的天数
int tm_yday; // 从 1 月 1 日开始的天数
int tm_isdst; // 日光节约时间的小时
}
以下是在 C 或 C++ 中处理日期和时间时使用的常用函数。这些函数都是标准 C 和 C++ 库的一部分,可以通过下面的 C++ 标准库参考查看详细信息。
| 序号 | 函数与用途 |
|---|---|
| 1 | time_t time(time_t *time); 此函数返回系统当前日历时间,以自 1970 年 1 月 1 日起经过的秒数表示。如果系统没有时间,则返回 .1。 |
| 2 | char *ctime(const time_t *time); 此函数返回一个字符串指针,格式为 day month year hours:minutes:seconds year\n\0。 |
| 3 | struct tm *localtime(const time_t *time); 此函数返回一个指向 tm 结构体的指针,表示本地时间。 |
| 4 | clock_t clock(void); 此函数返回调用程序运行时间的近似值。如果时间不可用,则返回 .1。 |
| 5 | char * asctime ( const struct tm * time ); 此函数返回一个字符串指针,包含由 time 指向的结构中存储的信息,并转换为以下格式:day month date hours:minutes:seconds year\n\0 |
| 6 | struct tm *gmtime(const time_t *time); 此函数返回一个指向 tm 结构体的指针,表示协调世界时 (UTC),本质上是格林威治标准时间 (GMT)。 |
| 7 | time_t mktime(struct tm *time); 此函数返回由 time 指向的结构中找到的时间的日历时间等价值。 |
| 8 | double difftime ( time_t time2, time_t time1 ); 此函数计算 time1 和 time2 之间的秒数差。 |
| 9 | size_t strftime(); 此函数可用于将日期和时间格式化为特定格式。 |
当前日期和时间
假设您想获取当前系统日期和时间,可以是本地时间或协调世界时 (UTC)。
示例
以下示例展示了如何实现:
#include <iostream>
#include <ctime>
using namespace std;
int main() {
// 基于当前系统的当前日期/时间
time_t now = time(0);
// 将 now 转换为字符串形式
char* dt = ctime(&now);
cout << "The local date and time is: " << dt << endl;
// 将 now 转换为 UTC 的 tm 结构体
tm *gmtm = gmtime(&now);
dt = asctime(gmtm);
cout << "The UTC date and time is:"<< dt << endl;
}
上述代码编译并执行后,将产生以下结果:
The local date and time is: Sat Jan 8 20:07:41 2011 The UTC date and time is:Sun Jan 9 03:07:41 2011
使用 struct tm 格式化时间
tm 结构在 C 或 C++ 中处理日期和时间时非常重要。该结构以 C 结构的形式存储日期和时间,如上所述。大多数与时间相关的函数都会使用 tm 结构。以下是一个示例,它使用了各种日期和时间相关的函数以及 tm 结构 −
在本章中使用结构时,我假设您对 C 结构以及如何使用箭头 -> 操作符访问结构成员有基本的了解。
示例
#include <iostream>
#include <ctime>
using namespace std;
int main() {
// 当前系统时间为基础的当前日期/时间
time_t now = time(0);
cout << "自 1970 年 1 月 1 日以来的秒数:: " << now << endl;
tm *ltm = localtime(&now);
// 打印 tm 结构的各个组件。
cout << "年份:" << 1900 + ltm->tm_year<<endl;
cout << "月份: "<< 1 + ltm->tm_mon<< endl;
cout << "日期: "<< ltm->tm_mday << endl;
cout << "时间: "<< 5+ltm->tm_hour << ":";
cout << 30+ltm->tm_min << ":";
cout << ltm->tm_sec << endl;
}
上述代码编译并执行后,将产生以下结果 −
Number of sec since January 1,1970 is:: 1588485717 Year:2020 Month: 5 Day: 3 Time: 11:31:57