【问题标题】:Store members of date in different variables将日期成员存储在不同的变量中
【发布时间】:2017-01-14 13:21:35
【问题描述】:

目前我正在运行以下代码

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 中。怎么做?

【问题讨论】:

  • 放一个你尝试过的示例代码......
  • 我想要一辆新车。最好是红色。
  • 那么问题是什么?你有没有遇到任何具体的问题?如果您甚至不知道从哪里开始,请阅读一本好的 C++ 书籍。通过反复试验或通过互联网上的随机 sn-ps 学习 C++ 是行不通的。

标签: c++ c ubuntu time


【解决方案1】:

你要的函数是localtime

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

来自man page

struct tm *localtime(const time_t *timep);

localtime() 函数将日历时间timep 转换为 分解的时间表示,相对于用户的表示 指定的时区。该函数的行为就像它调用了tzset(3) 和 设置外部变量tzname 与当前的信息 timezone, timezone 与 Coordinated Universal 的区别 时间 (UTC) 和当地标准时间(以秒为单位)和日光 如果夏令时规则在某些部分适用,则非零值 那一年。返回值指向一个静态分配的struct 这可能会被后续调用任何日期和 时间函数。

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

【讨论】:

    【解决方案2】:

    如果您想有时间查找__TIMESTAMP__ 变量。它应该是这样的:12 Sat 16 12:00:00

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多