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

标签 c++ chrono localtime ctime

我完全希望这会在一两天内关闭,因为它是一个主观主题,但无论如何:为什么在 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!"

现在将其与 C# 进行比较(例如):
Console.WriteLine(DateTime.Now.ToString("%d-%m-%Y %T")); // Well that was easy!

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

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

最佳答案

所有的tm stuff 继承自 C。C 代码与带有输出参数和返回代码的函数一起工作,因此代码往往很复杂。我们以文件 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 才尝试!
这是 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";
}

( live demo )

关于c++ - 为什么在 C++ 中获取日期和/或时间如此复杂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59509959/

相关文章:

c++ - 几何 -> OpenGL

c++ - 如何让 boost::spirit 停止解析关键字?

c++ - 与 std::chrono::system_clock/std::chrono::high_resolution_clock 的时差

c# - 使用 DateTime 时区

c++ - 将 YYMMDD 转换为 YYYYMMDD 并对它们进行排序

c++ - 在gdb中显示当前函数的调用函数

c++ - 如何获得几个 chrono::time_points 的平均值

java - LocalTime.MIDNIGHT 与 LocalTime.MIN - 有什么区别吗?

java - 使用 "hh:mm"Java 操作