我需要制作一个需要时间戳记的时间(以毫秒为单位的时间,类型long
)并将其转换为可读时间(YMD H:M:S);但是,在那之后,我必须重载该函数,以便如果该函数未获取参数,它将返回当前日期。
我知道如何使函数从给定的长参数转换为可读时间,但是我不知道如何重载函数。
#include <iostream>
#include <cstdio>
#include <ctime>
#include <string>
using namespace std;
string timeToString(long timestamp)
{
const time_t rawtime = (const time_t)timestamp;
struct tm * dt;
char timestr[30];
char buffer [30];
dt = localtime(&rawtime);
strftime(timestr, sizeof(timestr), "%Y-%m-%d %X", dt);
sprintf(buffer,"%s", timestr);
string stdBuffer(buffer);
return stdBuffer;
}
int main()
{
cout << timeToString(1538123990) << "\n";
}
首先(如注释中所述),您应该真正将Modern C ++库的std::chrono
函数用于时间操作。但是,坚持使用已有的基本代码,您只需为函数的参数提供默认值即可timeToString
。这个值在实际意义上应该是无意义的,并且是您永远不会真正通过的值。我-1
在下面的示例中选择了它,因为您不太可能使用负时间戳。
如果使用参数调用该函数,则使用该值;否则,将使用该值。否则,将使用给定的默认值调用该函数。然后,我们可以调整代码以检查该值,如下所示:
#include <iostream>
#include <ctime>
#include <string>
std::string timeToString(long timestamp = -1)
{
time_t rawtime; // We cannot (now) have this as "const"
if (timestamp < 0) rawtime = time(nullptr); // Default parameter:- get current time
else rawtime = static_cast<time_t>(timestamp); // Otherwise convert the given argument
struct tm* dt = localtime(&rawtime);
char timestr[30];
// char buffer[30]; // Redundant (see below)
strftime(timestr, sizeof(timestr), "%Y-%m-%d %X", dt);
// sprintf(buffer, "%s", timestr); // This just makes a copy of the same string!
return std::string(timestr);
}
int main()
{
std::cout << timeToString(1538123990) << "\n";
std::cout << timeToString() << "\n"; // No parameter - function will get "-1" instead!
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句