【发布时间】:2021-01-31 11:06:29
【问题描述】:
我需要创建一个函数,它需要一个时间戳(以毫秒为单位的时间,输入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";
}
【问题讨论】:
-
您的教师需要了解
std::chrono库并停止将 C 作为 C++ 进行教学 -
同意@Casey