使用 std::chrono 在 C++ 中输出日期和时间

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

Outputting Date and Time in C++ using std::chrono

c++datec++11timechrono

提问by const_ref

I have been upgrading some old code and have been trying to update to c++11 where possible. The following code is how I used to display the time and date in my program

我一直在升级一些旧代码,并在可能的情况下尝试更新到 c++11。以下代码是我用来在程序中显示时间和日期的方式

#include <iostream>
#include <string>
#include <stdio.h>
#include <time.h>

const std::string return_current_time_and_date() const
{
    time_t now = time(0);
    struct tm tstruct;
    char buf[80];
    tstruct = *localtime(&now);
    strftime(buf, sizeof(buf), "%Y-%m-%d %X", &tstruct);
    return buf;
}

I would like to output the current time and date in a similar format using std::chrono(or similar) but am unsure how to go about doing so. Any help would be greatly appreciated. Thanks

我想使用 std::chrono(或类似格式)以类似格式输出当前时间和日期,但我不确定如何去做。任何帮助将不胜感激。谢谢

回答by bames53

The <chrono>library only deals with time and not dates, except for the system_clockwhich has the ability to convert its timepoints to time_t. So using <chrono>for dates will not improve things much. Hopefully we get something like chrono::datein the not too distant future.

<chrono>库只处理时间而不处理日期,除了system_clock能够将其时间点转换为time_t. 所以使用<chrono>日期不会有太大的改善。希望我们chrono::date在不久的将来能得到类似的东西。

That said, you can use <chrono>in the following way:

也就是说,您可以通过<chrono>以下方式使用:

#include <chrono>  // chrono::system_clock
#include <ctime>   // localtime
#include <sstream> // stringstream
#include <iomanip> // put_time
#include <string>  // string

std::string return_current_time_and_date()
{
    auto now = std::chrono::system_clock::now();
    auto in_time_t = std::chrono::system_clock::to_time_t(now);

    std::stringstream ss;
    ss << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d %X");
    return ss.str();
}

Note that std::localtimemay cause data races. localtime_ror similar functions may be available on your platforms.

请注意,这std::localtime可能会导致数据竞争。localtime_r或类似的功能可能在您的平台上可用。

Update:

更新:

Using a new version of Howard Hinnant's date libraryyou can write:

使用新版本的 Howard Hinnant日期库,您可以编写:

#include "date.h"
#include <chrono>
#include <string>
#include <sstream>

std::string return_current_time_and_date() {
  auto now = std::chrono::system_clock::now();
  auto today = date::floor<days>(now);

  std::stringstream ss;
  ss << today << ' ' << date::make_time(now - today) << " UTC";
  return ss.str();
}

This will print out something like "2015-07-24 05:15:34.043473124 UTC".

这将打印出类似“2015-07-24 05:15:34.043473124 UTC”的内容。



On an unrelated note, returning constobjects has become undesirable with C++11; const return values cannot be moved from. I also removed the trailing const because trailing const is only valid for member functions and this function has no need to be a member.

在一个不相关的注释中,返回const对象在 C++11 中变得不可取;不能移动 const 返回值。我还删除了尾随 const,因为尾随 const 仅对成员函数有效,而此函数无需成为成员。

回答by Jayhello

An example:

一个例子:

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

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

    std::string s(30, '
#include <iostream>
#include <chrono>
#include <ctime>
#include <time.h>
#include <iomanip>


int main() {
  std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
  std::time_t currentTime = std::chrono::system_clock::to_time_t(now);
  std::chrono::milliseconds now2 = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
  struct tm currentLocalTime;
  localtime_r(&currentTime, &currentLocalTime);
  char timeBuffer[80];
  std::size_t charCount { std::strftime( timeBuffer, 80,
                                         "%D %T",
                                          &currentLocalTime)
                         };

  if (charCount == 0) return -1;

  std::cout << timeBuffer << "." << std::setfill('0') << std::setw(3) << now2.count() % 1000 << std::endl;
  return 0;
}
'); std::strftime(&s[0], s.size(), "%Y-%m-%d %H:%M:%S", std::localtime(&now)); return s; } int main(){ std::cout<<getTimeStr()<<std::endl; return 0; }

Output as below:

输出如下:

enter image description here

在此处输入图片说明

回答by rodolk

For getting also milliseconds, I use chrono and C function localtime_r which is thread-safe (in opposition to std::localtime).

为了获得毫秒,我使用了 chrono 和 C 函数 localtime_r,它是线程安全的(与 std::localtime 相对)。

void TimeTest()
{
    auto n = std::chrono::system_clock::now();
    auto in_time_t = std::chrono::system_clock::to_time_t(n);
    std::tm buf;
    localtime_s(&buf, &in_time_t);
    std::cout << std::put_time(&buf, "%Y-%m-%d %X") << std::endl;

}

// I just added date.h from this link's guthub to the project.
// https://howardhinnant.github.io/date/date.html
void TimeTest1() {
    auto now = std::chrono::system_clock::now();
    auto today =  floor<date::days>(std::chrono::system_clock::now());
    std::cout << date::year_month_day{ today } << ' ' << date::make_time(now - today) << std::endl;
}

// output is 
// 2018-04-08 21:19:49
// 2018-04-08 18:19:49.8408289

For format: http://www.cplusplus.com/reference/ctime/strftime/

格式:http: //www.cplusplus.com/reference/ctime/strftime/

回答by Yaniv

bames53 solutions are good, but do not compile on my VS2017. The solution with ctime does not compile because localtime is very deprecated. The one with date.h does not compile with the current date.h I just took off github even though the documentation says they should, because today cannot be streamed as is. I omitted the includes but here is code that works:

bames53 解决方案很好,但不能在我的 VS2017 上编译。使用 ctime 的解决方案无法编译,因为 localtime 非常不推荐使用。带有 date.h 的那个不能用当前的 date.h 编译,尽管文档说他们应该删除 github,但我刚刚删除了 github,因为今天不能按原样流式传输。我省略了包含,但这里是有效的代码:

#include <boost/lexical_cast.hpp>
#include <ctime>

std::string return_current_time_and_date() {
    auto current_time = std::time(0);
    return boost::lexical_cast<std::string>(std::put_time(std::gmtime(& current_time), "%Y-%m-%d %X"));
}

Feel free to fix bames53 solution and delete mine. My text just won't fit in a comment. I'm sure it can save many people from grief.

随意修复 bames53 解决方案并删除我的。我的文字不适合评论。我相信它可以使许多人免于悲伤。

回答by Xavier Lamorlette

You can improve the answer from @bames53 by using Boost lexical_cast instead of string stream manipulations.

您可以通过使用 Boost lexical_cast 而不是字符串流操作来改进@bames53 的答案。

Here is what I do:

这是我所做的:

##代码##