Current date and time as string
265,762
Solution 1
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;
}
Solution 2
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;
}
Solution 3
you can use asctime() function of time.h to get a string simply .
time_t _tm =time(NULL );
struct tm * curtime = localtime ( &_tm );
cout<<"The current date/time is:"<<asctime(curtime);
Sample output:
The current date/time is:Fri Oct 16 13:37:30 2015
Solution 4
Using C++ in MS Visual Studio 2015 (14), I use:
#include <chrono>
string NowToString()
{
chrono::system_clock::time_point p = chrono::system_clock::now();
time_t t = chrono::system_clock::to_time_t(p);
char str[26];
ctime_s(str, sizeof str, &t);
return str;
}
Solution 5
#include <chrono>
#include <iostream>
int main()
{
std::time_t ct = std::time(0);
char* cc = ctime(&ct);
std::cout << cc << std::endl;
return 0;
}
Author by
Katie
A girl who just loves programming :)) (but still learns ^^)
Updated on July 08, 2022Comments
-
Katie almost 2 years
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; }
-
Mat almost 11 years
-
Some programmer dude almost 11 yearsWouldn't it be simpler to use
std::strftime
? -
M456 almost 11 years
-
maverik almost 11 yearsHere is a question (and answer) about how to do this using boost (if you somehow cannot use C++11):
-
-
Matthieu M. almost 11 yearsAnd what if it overflows the buffer ? I suppose there should be a return value to
strftime
that you need to inspect in real code no ? -
Rafael Baptista almost 11 yearsIt doesn't take much thinking for any given format string to compute a maximum possible string length.
-
Yuriy Petrovskiy over 9 years
std::put_time
is still missing in gcc 4.9. -
Michael Trouw about 9 yearsI don't understand why you can pass rawtime by value on the 10th line from the top, as time acceps a pointer to a time_t type : cplusplus.com/reference/ctime/time In the example on that page they used time() the same way which i don't understand. Can anyone explain me this?
-
max about 9 yearsThere's an
&
there. That means instead of the contents of therawtime
variable, it's address in memory will be passed... which is what is stored in a pointer variable. -
Aconcagua about 9 yearsNo, you can't: asctime does not deliver the date/time format requested in the question!
-
SmallChess almost 9 yearsgcc 5.0 has it, but not the earlier versions.
-
SmallChess over 8 years@Aconcagua While it doesn't, it does give you time in a string. The code is clean and concise.
-
Aconcagua over 8 yearsClean and concise code does not help if it does not provide what one wants or needs. Want a truck (string), you get one. Wanting to transport liquids, you need a tanker truck and won't be happy getting a dump truck...
-
solendil over 8 yearsNice answer, but asctime() has the VERY bad idea of returning a LF terminated String...
-
scrutari about 8 yearsTo get milliseconds: auto now = std::chrono::system_clock::now(); std::chrono::time_point<std::chrono::system_clock> epoch; int ms = std::chrono::duration_cast<std::chrono::milliseconds>(now - epoch).count() % 1000;
-
Admin over 7 years@soon I have a question. In my code, I have a function that is supposed to return a time. What should be the return type of a function, that returns the current time?
-
awesoon over 7 years@ArnavBorborah, it depends. You may return time in Unix format, Boost Local date time or create your own type.
-
Homer6 over 7 yearslocaltime is not thread safe. Consider using localtime_r instead.
-
Roi Danton over 6 yearsFurthermore
asctime
is not locale-sensitive likestrftime
is. -
Melebius over 5 yearsThank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you’ve made, like
#include
s. -
Steve Smith over 5 yearsWhat does this actually return?
-
SimonC almost 5 yearsSadly this function returns 0 and doesn't format the date/time correctly on Windows 10. (At least for me).
-
Ruslan over 4 years@Homer6 it's not standard. See also: Will getting the current date/time be thread-safe in C++20?
-
phamuc over 2 years@Steve Smith The output is: Tue Sep 14 14:17:16 2021
-
Howard Hinnant almost 2 yearsClarification: This gives the current UTC time, whereas the OP appears to want the current local time according to his computer's currently set time zone. This is also easy in C++20.