用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; // 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
}

假设您要以本地时间或世界标准时间(UTC)检索当前系统日期和时间。以下是实现相同目的的示例–

示例

#include <iostream>
#include <ctime>
using namespace std;
int main() {
   //基于当前系统的当前日期/时间
   time_t now = time(0);
   char* dt = ctime(&now); // convert now to string form
   cout << "The local date and time is: " << dt << endl;
   //现在将UTC转换为tm struct-
   tm *gmtm = gmtime(&now);
   dt = asctime(gmtm);
   cout << "UTC日期和时间是:"<< dt << endl;
}

输出结果

The local date and time is: Fri Mar 22 13:07:39 2019
UTC日期和时间是:Fri Mar 22 07:37:39 2019