【问题标题】:How to get current date and time? [duplicate]如何获取当前日期和时间? [复制]
【发布时间】:2012-01-10 17:39:15
【问题描述】:

如何获取当前日期 d/m/y。我需要它们有 3 个不同的变量而不是一个,例如 day=d; month=m; year=y;

【问题讨论】:

标签: c++ time


【解决方案1】:

对于 linux,您可以使用 'localtime' 函数。

#include <time.h>

time_t theTime = time(NULL);
struct tm *aTime = localtime(&theTime);

int day = aTime->tm_mday;
int month = aTime->tm_mon + 1; // Month is 0 - 11, add 1 to get a jan-dec 1-12 concept
int year = aTime->tm_year + 1900; // Year is # years since 1900

【讨论】:

  • 你的意思是localtime(&time(NULL)); ?
  • 我更正了答案,因为它不会按原样编译。您不能通过指针(即只是一个数字)进行右值,因此您需要先将其放入变量中
【解决方案2】:

这里是 chrono 方式 (C++0x) - 在 http://ideone.com/yFm9P

上实时查看
#include <chrono>
#include <ctime>
#include <iostream>

using namespace std;

typedef std::chrono::system_clock Clock;

int main()
{
    auto now = Clock::now();
    std::time_t now_c = Clock::to_time_t(now);
    struct tm *parts = std::localtime(&now_c);

    std::cout << 1900 + parts->tm_year  << std::endl;
    std::cout << 1    + parts->tm_mon   << std::endl;
    std::cout <<        parts->tm_mday  << std::endl;

    return 0;
}

【讨论】:

  • ideone.com/yFm9P上实时发布了工作示例
  • @PaoloM std::time_t 需要标头
  • 抱歉,在 gcc 4.8 下编译时没有 &lt;ctime&gt;。它肯定会被&lt;chrono&gt; 收录。
【解决方案3】:

ctime 库提供了这样的功能。

同时检查this。这是另一篇文章,可能会对您有所帮助,具体取决于您的平台。

【讨论】:

  • #include &lt;ctime&gt; #include &lt;iostream&gt; using namespace std; int main() { time_t t = time(0); // get time now struct tm * now = localtime( &amp; t ); cout &lt;&lt; (now-&gt;tm_year + 1900) &lt;&lt; '-' &lt;&lt; (now-&gt;tm_mon + 1) &lt;&lt; '-' &lt;&lt; now-&gt;tm_mday &lt;&lt; endl; } 谢谢
猜你喜欢
  • 2012-12-23
  • 2011-01-01
  • 2015-08-16
  • 1970-01-01
  • 2012-12-04
  • 2019-12-22
  • 1970-01-01
  • 2018-06-19
相关资源
最近更新 更多