由于它是一个主观的话题,我完全希望这能在一两天内完成,但是无论如何,这是为什么:为什么要用至少5行代码才能在C ++中获得日期/时间?
这是我学习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 ++中一个更短的方法吗? MTIA!
答案 0 :(得分:11)
所有tm
的东西都是从C继承的。C代码与带有输出参数和返回代码的函数一起工作,因此代码易于卷积。让我们以文件I / O为例:
FILE *file;
file = fopen("foo", "w");
fprintf(file, "%d", /* some number */);
fclose(file);
vs
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";
}