c++ - 将日期成员存储在不同的变量中

标签 c++ c ubuntu time

目前我正在运行以下代码

int main() {

    while(1)

        {
            time_t current = time(NULL);
            cout << ctime(&current)<< endl;
        }
}

我的输出如下所示:

2017 年 1 月 15 日星期日 00:03:25

2017 年 1 月 15 日星期日 00:03:25

因为小时是 00,分钟是 03,秒是 25。我想将 00 存储在某个整数变量中,比如说 int hrs,将 03 存储在变量 int min 和 25 位于变量 int sec 中。怎么做?

最佳答案

您想要的函数是本地时间

该函数获取time_t的地址并返回一个指向struct tm的指针,其中包含 segmentation 为年、月、日、小时的日期和时间,分钟和秒。

来自man page :

struct tm *localtime(const time_t *timep);

The localtime() function converts the calendar time timep to broken-down time representation, expressed relative to the user's specified timezone. The function acts as if it called tzset(3) and sets the external variables tzname with information about the current timezone, timezone with the difference between Coordinated Universal Time (UTC) and local standard time in seconds, and daylight to a nonzero value if daylight savings time rules apply during some part of the year. The return value points to a statically allocated struct which might be overwritten by subsequent calls to any of the date and time functions.

struct tm的定义如下:

struct tm {
    int tm_sec;         /* seconds */
    int tm_min;         /* minutes */
    int tm_hour;        /* hours */
    int tm_mday;        /* day of the month */
    int tm_mon;         /* month */
    int tm_year;        /* year */
    int tm_wday;        /* day of the week */
    int tm_yday;        /* day in the year */
    int tm_isdst;       /* daylight saving time */
};

关于c++ - 将日期成员存储在不同的变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41650465/

相关文章:

linux - Elasticsearch 用户运行的未知进程

ruby - 在 UBUNTU 中从 TTF 文件中查找 FontName

c++ - 串行数据最初错误 C++

javascript - 如何在 windows7(WebRTC,C++)的 chrome(CEF3)中设置音频输出(扬声器)

c - 完全无法理解在数组中存储像素数据的概念

c - 如何从客户端调用 C 服务器中的函数

python - pydrive:尝试将文件从远程服务器上传到 Google Drive

c++ - 针对 dll/lib 的 cmake 链接

C++ : Pick portions/data from a string having fixed format

c - 从二进制文件读取结构时出现问题