C++11 获取当前日期和时间作为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34963738/
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 14:27:46  来源:igfitidea点击:

C++11 get current date and time as string

c++datetimec++11

提问by kiigass

What is the state of the art way to get date and time as string in c++11?

在 C++11 中以字符串形式获取日期和时间的最先进方法是什么?

I know about std::put_time, but the reference says I shall use it only in streams.

我知道std::put_time,但参考资料说我只能在流中使用它。

There is std::chrono::system_clockwhich provides to_time_treturning the time as time_tand lacking the date, doesn't it?

std::chrono::system_clock哪个提供to_time_t返回时间time_t和缺少日期的功能,不是吗?

I could use a stringstream like bames53: Outputting Date and Time in C++ using std::chronobut that seems to be a workaround.

我可以使用像 bames53: Outputing Date and Time in C++ using std::chrono 这样的字符串流,但这似乎是一种解决方法。

回答by Howard Hinnant

Using Howard Hinnant's free, open-source header-only datetime library, you can get the current UTC time as a std::stringin a single line of code:

使用Howard Hinnant 的免费、开源仅标头日期时间库,您可以std::string在一行代码中获取当前的 UTC 时间:

std::string s = date::format("%F %T", std::chrono::system_clock::now());

I just ran this, and the string contains:

我刚刚运行了这个,字符串包含:

2017-03-30 17:05:13.400455

That's right, it even gives you the full precision. If you don't like that format, all of the strftimeformatting flags are available. If you want your local time, there is a timezone libraryalso available, though it is not header only.

没错,它甚至可以为您提供完整的精度。如果您不喜欢这种格式,strftime则可以使用所有格式标志。如果您想要本地时间,也可以使用时区库,尽管它不仅仅是标题。

std::string s = date::format("%F %T %Z", date::make_zoned(date::current_zone(),
                                         std::chrono::system_clock::now()));

Output:

输出:

2017-03-30 13:05:13.400455 EDT

回答by Yam Marcovic

Firstly, std::time_tindeed captures both date and time, since it generally represents seconds from January 1st, 1970.

首先,std::time_t确实捕获日期和时间,因为它通常表示从 1970 年 1 月 1 日开始的秒数。

There is no greatsupport for handling dates in C++11. You still have to depend on boost if you don't wish to do it, mostly, manually. Here's how to do it manually.

在 C++11 中对处理日期没有很好的支持。如果您不想这样做,您仍然必须依赖 boost,主要是手动。这是手动执行此操作的方法。

You can use it—in a thread-safe way—together with any std::chrono::*clock, such as std::system_clock, like this:

您可以以线程安全的方式将它与 any 一起使用std::chrono::*clock,例如std::system_clock,如下所示:

std::string get_date_string(std::chrono::time_point t) {
  auto as_time_t = std::chrono::system_clock::to_time_t(t);
  struct tm tm;
  if (::gmtime_r(&as_time_t, &tm))
    if (std::strftime(some_buffer, sizeof(some_buffer), "%F", &tm))
      return std::string{some_buffer};
  throw std::runtime_error("Failed to get current date as string");
}

Somewhere else, you can issue:

在其他地方,您可以发出:

get_date_string(std::system_clock::now());

The relatively goodthing about this solution is that, at the API level, you're still using modern, portable C++ concepts such as std::chrono::time_point, and of course, std::string.

比较好的对这一解决办法的事情是,在API级别,你还在使用现代的,可移植的C ++概念,如std::chrono::time_point,当然,std::string

回答by Timmmm

Simpler:

更简单:

string CurrentDate()
{
    std::time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());

    char buf[100] = {0};
    std::strftime(buf, sizeof(buf), "%Y-%m-%d", std::localtime(&now));
    return buf;
}

Adjust the format as appropriate for the time too.

也根据时间调整格式。

Note that I suspect this will not work well for multithreaded code since std::localtime()returns a pointer to an internal struct.

请注意,我怀疑这不适用于多线程代码,因为它std::localtime()返回一个指向内部结构的指针。

回答by Angus Comber

timestamp like this;

像这样的时间戳;

#include <iostream>
#include <chrono>
#include <ctime>

int main() {

    std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
    std::time_t start_time = std::chrono::system_clock::to_time_t(now);
    char timedisplay[100];
    struct tm buf;
    errno_t err = localtime_s(&buf, &start_time);
    if (std::strftime(timedisplay, sizeof(timedisplay), "%H:%M:%S", &buf)) {
        std::cout << timedisplay << '\n';
    }
}

Date in a similar manner.

以类似的方式日期。

回答by Abhishek Rathore

You can use the code snippet given below as it will serve your purpose. Here use time.hheader file for required localtime()function and then using the strftime()function with required parameters will give the output and it returns it as a string.

您可以使用下面给出的代码片段,因为它将满足您的目的。这里对所需的localtime()函数使用time.h头文件,然后使用带有所需参数的strftime()函数将给出输出并将其作为字符串返回。

#include <iostream>
#include <string>
#include <time.h>
std::string current_date();
std::string current_time();
int main(){
    std::cout<<"Current date => "<<current_date()<<"\n";
    std::cout<<"Current time => "<<current_time()<<"\n";
}
std::string current_date(){
    time_t now = time(NULL);
    struct tm tstruct;
    char buf[40];
    tstruct = *localtime(&now);
    //format: day DD-MM-YYYY
    strftime(buf, sizeof(buf), "%A %d/%m/%Y", &tstruct);
    return buf;
}
std::string current_time(){
    time_t now = time(NULL);
    struct tm tstruct;
    char buf[40];
    tstruct = *localtime(&now);
    //format: HH:mm:ss
    strftime(buf, sizeof(buf), "%X", &tstruct);
    return buf;
}