C++ 如何获取当前日期和时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8343676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:24:12  来源:igfitidea点击:

How to get current date and time?

c++time

提问by Wizard

How to get current date d/m/y. I need that they have 3 different variables not one, for example day=d; month=m; year=y;.

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

回答by Petesh

For linux, you would use the 'localtime'function.

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

回答by sehe

Here is the chronoway (C++0x) - see it live on http://ideone.com/yFm9P

这是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;
}

回答by TurnsCoffeeIntoScripts

The ctimelibrary provide such functionnality.

的ctime库提供这样的functionnality。

Also check this. It is an other post that might help you out depending on your platform.

也检查这个。这是另一篇文章,可能会根据您的平台为您提供帮助。