迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > C++ >

C++ 中的 time(NULL) 函数

作者:迹忆客 最近更新:2023/08/24 浏览次数:

本文将讨论 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
};

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Arduino 中停止循环

发布时间:2024/03/13 浏览次数:444 分类:C++

可以使用 exit(0),无限循环和 Sleep_n0m1 库在 Arduino 中停止循环。

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()函数在串口监视器上显示变量值。

Arduino if 语句

发布时间:2024/03/13 浏览次数:123 分类:C++

可以使用 if 语句检查 Arduino 中的不同条件。

Arduino ICSP

发布时间:2024/03/13 浏览次数:214 分类:C++

ICSP 引脚用于两个 Arduino 之间的通信以及对 Arduino 引导加载程序进行编程。

使用 C++ 编程 Arduino

发布时间:2024/03/13 浏览次数:127 分类:C++

本教程将讨论使用 Arduino IDE 在 C++ 中对 Arduino 进行编程。

Arduino 中的子程序

发布时间:2024/03/13 浏览次数:168 分类:C++

可以通过在 Arduino 中声明函数来处理子程序。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便