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

Why is it so convoluted to get the date and/or time in C++?

我完全希望它能在一两天内结束,因为它是一个有点主观的话题,但无论如何:为什么至少需要 5 行代码才能在 C++ 中获得 date/time?

这是我学会用 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!"

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

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

这种胡说八道是否有充分的理由,或者它只是归结为 C++ 适用于开发人员 wants/needs 更多控制的低级内容的普遍想法?

作为狂热的代码高尔夫球手,我会在一周的任何一天的第一天选择第二个选项,因为较短的代码通常更清晰、更易读、更容易调试,而且通常 更好 恕我直言。那么 C++ 中是否有我缺少的更短的方法? MTIA!

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

FILE *file;
file = fopen("foo", "w");
fprintf(file, "%d", /* some number */);
fclose(file);

std::ofstream ofs{"foo"};
ofs << /* some number */;

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


...直到 C++20,其中 Howard Hinnant's date library 被选入标准库!该库非常轻量级,所以不要等到 C++20 后再尝试! 这是自述文件中的示例:

#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";
}

(live demo)