如何显示时间戳中的时间,并在没有争论的情况下显示当前时间



我需要制作一个函数,该函数使用时间戳(以毫秒为单位的时间,键入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++库的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;
}

最新更新