C++ 中的 time(NULL) 函数
本文将讨论 C++ 中的 time(NULL) 函数。
C++ 中的 time(NULL) 函数
time() 函数,参数为 NULL,time(NULL),返回自 1970 年 1 月 1 日以来的当前日历时间,以秒为单位。 Null 是一个内置常量,其值为 0,是一个类似于 0 的指针,除非 CPU 支持特殊的 空指针的位模式。
假设您传递一个指向 time_t 变量的指针; 该变量将指向当前时间。 time_t 是 ISO C++ 库中定义用于存储和利用系统时间值的数据类型。
此类值类型是从标准 time()
库函数返回的。 它定义在time.h头文件中,是一个无符号长整型,大小为8字节。
示例代码:
#include<iostream>
#include<time.h>
using namespace std;
int main(){
time_t seconds;
seconds = time(NULL);
cout<<"Time in seconds is = "<<seconds<<endl;
}
输出:
Time in seconds is = 1650710906
我们定义了一个time_t数据类型的变量seconds,并将其初始化为函数time(NULL)的返回值。 该函数返回 1970 年 1 月 1 日以来的时间(以秒为单位),我们在最后打印了结果。
现在,以秒为单位的读取时间对于人类来说可能不方便理解,因此应该有某种机制将以秒为单位的时间转换为可理解的格式。 多亏了 C++ 库,我们有了如下的解决方案;
#include<iostream>
#include<time.h>
using namespace std;
int main(){
time_t seconds;
seconds = time(NULL);
struct tm* local_time = localtime(&seconds);
cout<<"Time in seconds " <<seconds<<endl;
cout<<"local time " << asctime(local_time);
}
输出:
Time in seconds 1650712161
local time Sat Apr 23 16:09:21 2022
struct tm是C/C++语言time.h头文件中的内置结构体,每个对象都包含机器上的日期和时间。 我们可以利用 tm 结构的这些成员按照我们想要的方式自定义我们的代码。
struct tm {
int tm_sec; // seconds, ranges from 0 to 59
int tm_min; // minutes, ranges from 0 to 59
int tm_hour; // hours, ranges from 0 to 23
int tm_mday; // day of the month, ranges from 1 to 31
int tm_mon; // month, ranges from 0 to 11
int tm_year; // The number of years since 1900
int tm_wday; // day of the week, ranges from 0 to 6
int tm_yday; // day in the year, ranges from 0 to 365
int tm_isdst; // daylight saving time
};
相关文章
Arduino 复位
发布时间:2024/03/13 浏览次数:315 分类:C++
-
可以通过使用复位按钮,Softwarereset 库和 Adafruit SleepyDog 库来复位 Arduino。
Arduino 的字符转换为整型
发布时间:2024/03/13 浏览次数:181 分类:C++
-
可以使用简单的方法 toInt()函数和 Serial.parseInt()函数将 char 转换为 int。
Arduino 串口打印多个变量
发布时间:2024/03/13 浏览次数:381 分类:C++
-
可以使用 Serial.print()和 Serial.println()函数在串口监视器上显示变量值。