I wrote a function to get a current date and time in format: DD-MM-YYYY HH:MM:SS
. It works but let's say, its pretty ugly. How can I do exactly the same thing but simpler?
string currentDateToString()
{
time_t now = time(0);
tm *ltm = localtime(&now);
string dateString = "", tmp = "";
tmp = numToString(ltm->tm_mday);
if (tmp.length() == 1)
tmp.insert(0, "0");
dateString += tmp;
dateString += "-";
tmp = numToString(1 + ltm->tm_mon);
if (tmp.length() == 1)
tmp.insert(0, "0");
dateString += tmp;
dateString += "-";
tmp = numToString(1900 + ltm->tm_year);
dateString += tmp;
dateString += " ";
tmp = numToString(ltm->tm_hour);
if (tmp.length() == 1)
tmp.insert(0, "0");
dateString += tmp;
dateString += ":";
tmp = numToString(1 + ltm->tm_min);
if (tmp.length() == 1)
tmp.insert(0, "0");
dateString += tmp;
dateString += ":";
tmp = numToString(1 + ltm->tm_sec);
if (tmp.length() == 1)
tmp.insert(0, "0");
dateString += tmp;
return dateString;
}
Since C++11 you could use std::put_time
from iomanip
header:
#include <iostream>
#include <iomanip>
#include <ctime>
int main()
{
auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
std::cout << std::put_time(&tm, "%d-%m-%Y %H-%M-%S") << std::endl;
}
std::put_time
is a stream manipulator, therefore it could be used together with std::ostringstream
in order to convert the date to a string:
#include <iostream>
#include <iomanip>
#include <ctime>
#include <sstream>
int main()
{
auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
std::ostringstream oss;
oss << std::put_time(&tm, "%d-%m-%Y %H-%M-%S");
auto str = oss.str();
std::cout << str << std::endl;
}