102

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;
}
4

7 Answers 7

213

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;
}
6
  • 35
    std::put_time is still missing in gcc 4.9. Aug 15, 2014 at 21:30
  • 5
    gcc 5.0 has it, but not the earlier versions.
    – SmallChess
    Jul 14, 2015 at 2:15
  • @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?
    – user5447628
    Sep 18, 2016 at 15:57
  • @ArnavBorborah, it depends. You may return time in Unix format, Boost Local date time or create your own type.
    – awesoon
    Sep 18, 2016 at 16:06
  • localtime is not thread safe. Consider using localtime_r instead.
    – Homer6
    Dec 26, 2016 at 20:56
140

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;
}
6
  • 3
    And 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 ? May 3, 2013 at 12:17
  • 6
    It doesn't take much thinking for any given format string to compute a maximum possible string length. May 3, 2013 at 13:05
  • 1
    I 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?
    – Michahell
    Jan 28, 2015 at 14:23
  • 1
    There's an & there. That means instead of the contents of the rawtime variable, it's address in memory will be passed... which is what is stored in a pointer variable.
    – max
    Jan 30, 2015 at 4:57
  • To 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;
    – scrutari
    Apr 27, 2016 at 10:56
29

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
5
  • 3
    No, you can't: asctime does not deliver the date/time format requested in the question!
    – Aconcagua
    Feb 2, 2015 at 15:44
  • 3
    @Aconcagua While it doesn't, it does give you time in a string. The code is clean and concise.
    – SmallChess
    Oct 16, 2015 at 2:36
  • 5
    Clean 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...
    – Aconcagua
    Oct 16, 2015 at 7:47
  • 4
    Nice answer, but asctime() has the VERY bad idea of returning a LF terminated String...
    – solendil
    Nov 9, 2015 at 10:56
  • 1
    Furthermore asctime is not locale-sensitive like strftime is.
    – Roi Danton
    Aug 1, 2017 at 8:51
18

With C++20, time point formatting (to string) is available in the (chrono) standard library. https://en.cppreference.com/w/cpp/chrono/system_clock/formatter

#include <chrono>
#include <format>
#include <iostream>

int main()
{
   const auto now = std::chrono::system_clock::now();
   std::cout << std::format("{:%d-%m-%Y %H:%M:%OS}", now) << '\n';
}

Output

13-12-2021 09:24:44

It works in Visual Studio 2019 (v16.11.5) with the latest C++ language version (/std:c++latest).

1
  • 1
    Clarification: 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. Jun 8, 2022 at 17:49
7

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;
}
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;
}
3
  • 3
    Thank 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 #includes.
    – Melebius
    Sep 13, 2018 at 12:29
  • 3
    What does this actually return? Sep 18, 2018 at 10:53
  • @Steve Smith The output is: Tue Sep 14 14:17:16 2021
    – phamuc
    Sep 14, 2021 at 12:18
2

I wanted to use the C++11 answer, but I could not because GCC 4.9 does not support std::put_time.

std::put_time implementation status in GCC?

I ended up using some C++11 to slightly improve the non-C++11 answer. For those that can't use GCC 5, but would still like some C++11 in their date/time format:

 std::array<char, 64> buffer;
 buffer.fill(0);
 time_t rawtime;
 time(&rawtime);
 const auto timeinfo = localtime(&rawtime);
 strftime(buffer.data(), sizeof(buffer), "%d-%m-%Y %H-%M-%S", timeinfo);
 std::string timeStr(buffer.data());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.