问题描述
我需要制作一个带有时间戳(以毫秒为单位的时间,键入long
)并将其转换为可读时间的函数(Y-M-D 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 ++库的keyEvent.metaKey
函数。但是,坚持使用已有的基本代码,您只需为std::chrono
函数的参数提供一个 default 值即可;这应该是一个在实际意义上毫无意义的值,并且是您实际上不会通过的值。在下面的示例中,我选择了timeToString
,因为您不太可能使用负时间戳。
如果该函数使用参数调用,则使用该值;否则,将使用给定的默认值调用该函数。然后,我们可以调整代码以检查该值,如下所示:
-1