如何获得当前的日期和时间?

时间:2011-12-01 15:17:52

标签: c++ time

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

3 个答案:

答案 0 :(得分:23)

对于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

答案 1 :(得分:10)

以下是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;
}

答案 2 :(得分:2)

ctime库提供了这样的功能。

同时检查this。根据您的平台,这是另一篇可能会帮助您的帖子。

相关问题