C++ 日期和时间
在本文中,我们将学习C++中的日期和时间格式。C++中没有完整的日期和时间格式,所以我们从C语言中继承它。要在C++中使用日期和时间,需要在程序中添加头文件 <ctime> 。
<ctime>
这个头文件有四个与时间相关的类型,如下:
- Clock_t – 表示时钟类型,是算术类型的别名。它表示时钟滴答数(以系统特定长度的时间单位计数)。Clock_t是由 clock()/. 返回的类型。
- Time_t – 表示时间类型。它表示通过函数 time() 返回的时间。它以整数值输出,表示00:00小时经过的秒数。
- Size_t – 是无符号整数类型的别名,表示以字节为单位的任何对象的大小。Size_t是 sizeof() 运算符的结果,用于打印大小和计数。
- tm – tm结构在C结构中保存日期和时间。它的定义如下:
struct tm {
    int tm_sec; // seconds of minutes from 0 to 61
    int tm_min; // minutes of hour from 0 to 59
    int tm_hour; // hours of day from 0 to 24
    int tm_mday; // day of month from 1 to 31
    int tm_mon; // month of year from 0 to 11
    int tm_year; // year since 1900
    int tm_wday; // days since sunday
    int tm_yday; // days since January 1st
    int tm_isdst; // hours of daylight savings time
}
C++中的日期和时间函数
| 函数名称 | 函数原型 | 函数描述 | 
|---|---|---|
| mktime | time_t mktime(struct tm *time); | 该函数将 mktime 转换为 time_t 或日历日期和时间。 | 
| ctime | char *ctime(const time_t *time); | 返回指向格式为“年 月 日 时:分:秒 年”的字符串的指针。 | 
| difftime | double difftime ( time_t time2, time_t time1 ); | 返回两个时间对象t1和t2之间的差值。 | 
| gmtime | struct tm *gmtime(const time_t *time); | 该函数以结构体的格式返回时间指针。时间以协调世界时(UTC)表示。 | 
| clock | clock_t clock(void); | 返回表示调用程序运行时间的近似值。如果不可用,则返回0.1。 | 
| localtime | struct tm *localtime(const time_t *time); | 该函数返回表示本地时间的tm结构指针。 | 
| time | time_t time(time_t *time); | 表示当前时间。 | 
| strftime | size_t strftime(); | 使用此函数,我们可以按特定的方式格式化日期和时间。 | 
| asctime | char * asctime ( const struct tm * time ); | 该函数将tm类型的对象转换为字符串,并返回字符串的指针。 | 
打印当前日期和时间的示例
以下是以UTC格式打印当前日期和时间的示例。
代码
#include  
#include 
using namespace std;
int main()
{
    time_t now = time(0); // get current dat/time with respect to system
    char* dt = ctime(&now); // convert it into string
    cout << "The local date and time is: " << dt << endl; // print local date and time
    tm* gmtm = gmtime(&now); // for getting time to UTC convert to struct
    dt = asctime(gmtm);
    cout << "The UTC date and time is:" << dt << endl; // print UTC date and time
}
输出
The local date and time is: Wed Sep 22 16:31:40 2021
The UTC date and time is: Wed Sep 22 16:31:40 2021
下面的代码告诉了如何打破tm结构,并使用 – >运算符独立打印每个属性。
代码
#include 
#include 
using namespace std;
int main()
{
    time_t now = time(0); // get current date and time
    cout << "Number of seconds since January 1,2021 is:: " << now << endl;
    tm* ltm = localtime(&now);
    // print various components of tm structure.
    cout << "Year:" << 1900 + ltm->tm_year << endl; // print the year
    cout << "Month: " << 1 + ltm->tm_mon << endl; // print month number
    cout << "Day: " << ltm->tm_mday << endl; // print the day
    // Print time in hour:minute:second
    cout << "Time: " << 5 + ltm->tm_hour << ":";
    cout << 30 + ltm->tm_min << ":";
    cout << ltm->tm_sec << endl;
}
输出
Number of seconds since January 1,2021 is:: 1632328553
Year:2021
Month: 9
Day: 22
Time: 21:65:53
 极客笔记
极客笔记