为什么在 C++ 中获取日期和/或时间如此复杂?

Ken*_*y83 8 c++ ctime localtime c++-chrono

我完全希望这会在一两天内关闭,因为这是一个主观的话题,但无论如何都要说:为什么在 C++ 中获取日期/时间至少需要 5 行代码?

这是我在 C 中学会的第一件事,但那是很久以前的事了……我记得当时我花了一段时间才掌握整个概念。现在我更有经验了,但是在习惯了 C# 和 Java 等高级语言之后,我真的很恼火,这么简单的事情需要所有这些:

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

using namespace std::chrono;

// First get an epoch value
auto time = system_clock::to_time_t(system_clock::now());

// Now we need a char buffer to hold the output
char timeString[20] = "";

// Oh and a tm struct too! Gotta have that, just to make it more complicated!
tm tmStruct;

// Oh and BTW, you can't just get your local time directly;
// you need to call localtime_s with the tm AND the time_t!
// Can't use localtime anymore since it's "unsafe"
localtime_s(&tmStruct, &time);

// Hurray! We finally have a readable string!!
strftime(timeString, 20, "%d-%m-%Y %T", &tmp);

cout << timeString << "Phew! I'm tired, I guess the time must be bedtime!"
Run Code Online (Sandbox Code Playgroud)

现在将其与 C# 进行比较(例如):

Console.WriteLine(DateTime.Now.ToString("%d-%m-%Y %T")); // Well that was easy!
Run Code Online (Sandbox Code Playgroud)

这种胡说八道是否有充分的理由,或者它是否只是归结为 C++ 用于开发人员想要/需要更多控制的低级东西的一般想法?

作为一个狂热的代码爱好者,我会在一周的第一天选择第二个选项,因为较短的代码通常更干净、更易读、更容易调试,而且通常更好恕我直言。那么我缺少的 C++ 中是否有更短的方法?马蒂亚!

L. *_* F. 11

所有的tm东西都是从 C 继承的。 C 代码与带有输出参数和返回码的函数一起工作,所以代码往往很复杂。我们仅以文件 I/O 为例:

FILE *file;
file = fopen("foo", "w");
fprintf(file, "%d", /* some number */);
fclose(file);
Run Code Online (Sandbox Code Playgroud)

对比

std::ofstream ofs{"foo"};
ofs << /* some number */;
Run Code Online (Sandbox Code Playgroud)

在这种情况下,C++ 标准库恰好不包含日期功能,这是一种耻辱......


...直到 C++20,Howard Hinnant 的日期库被选入标准库!该库非常轻量级,所以不要等到 C++20 才尝试!这是 README 文件中的示例:

#include "date.h"
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    auto now = system_clock::now();
    std::cout << "The current time is " << now << " UTC\n";
    auto current_year = year_month_day{floor<days>(now)}.year();
    std::cout << "The current year is " << current_year << '\n';
    auto h = floor<hours>(now) - sys_days{January/1/current_year};
    std::cout << "It has been " << h << " since New Years!\n";
}
Run Code Online (Sandbox Code Playgroud)

现场演示