I need to make a function which takes a timestamp (the time in milliseconds, type long
) and transforms it into readable time (Y-M-D H:M:S); however, after that, I have to overload the function such that if the function doesn't get a parameter it will return the current date.
I know how to make the function to transform from the given long parameter to readable time, but I don't know how to overload the function.
#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";
}
First of all (as mentioned in the comments) you should really be using the Modern C++ library's std::chrono
functions for your time operations. However, sticking with the basic code that you have, you can just provide a default value for the parameter of your timeToString
function; this should be a value that is meaningless in a real sense, and one that you would never actually pass. I have chosen -1
in the example below, as it is unlikely that you would be using a negative time stamp.
If the function is called with a parameter, then that value is used; otherwise, the function gets called with the given default value. We can then adjust the code to check for that value, as shown below:
#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;
}