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; }
today() method to get the current local date. By the way, date. today() returns a date object, which is assigned to the today variable in the above program. Now, you can use the strftime() method to create a string representing date in different formats.
The date() function already returns a string. Doing this : $date = date("D M d, Y G:i"); You'll have the current date in the $date variable, as a string -- no need for any additional operation.
C++ strftime() The strftime() function in C++ converts the given date and time from a given calendar time time to a null-terminated multibyte character string according to a format string. The strftime() function is defined in <ctime> header file.
Non C++11 solution: With the <ctime>
header, you could use strftime
. Make sure your buffer is large enough, you wouldn't want to overrun it and wreak havoc later.
#include <iostream> #include <ctime> int main () { time_t rawtime; struct tm * timeinfo; char buffer[80]; time (&rawtime); timeinfo = localtime(&rawtime); strftime(buffer,sizeof(buffer),"%d-%m-%Y %H:%M:%S",timeinfo); std::string str(buffer); std::cout << str; return 0; }
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With