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;
}
Share:
265,762
Katie
Author by

Katie

A girl who just loves programming :)) (but still learns ^^)

Updated on July 08, 2022

Comments

  • Katie
    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;
    }
    
  • Matthieu M.
    Matthieu M. almost 11 years
    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 ?
  • Rafael Baptista
    Rafael Baptista almost 11 years
    It doesn't take much thinking for any given format string to compute a maximum possible string length.
  • Yuriy Petrovskiy
    Yuriy Petrovskiy over 9 years
    std::put_time is still missing in gcc 4.9.
  • Michael Trouw
    Michael Trouw about 9 years
    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?
  • max
    max about 9 years
    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.
  • Aconcagua
    Aconcagua about 9 years
    No, you can't: asctime does not deliver the date/time format requested in the question!
  • SmallChess
    SmallChess almost 9 years
    gcc 5.0 has it, but not the earlier versions.
  • SmallChess
    SmallChess over 8 years
    @Aconcagua While it doesn't, it does give you time in a string. The code is clean and concise.
  • Aconcagua
    Aconcagua over 8 years
    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...
  • solendil
    solendil over 8 years
    Nice answer, but asctime() has the VERY bad idea of returning a LF terminated String...
  • scrutari
    scrutari about 8 years
    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;
  • Admin
    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
    awesoon over 7 years
    @ArnavBorborah, it depends. You may return time in Unix format, Boost Local date time or create your own type.
  • Homer6
    Homer6 over 7 years
    localtime is not thread safe. Consider using localtime_r instead.
  • Roi Danton
    Roi Danton over 6 years
    Furthermore asctime is not locale-sensitive like strftime is.
  • Melebius
    Melebius over 5 years
    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.
  • Steve Smith
    Steve Smith over 5 years
    What does this actually return?
  • SimonC
    SimonC almost 5 years
    Sadly this function returns 0 and doesn't format the date/time correctly on Windows 10. (At least for me).
  • Ruslan
    Ruslan over 4 years
  • phamuc
    phamuc over 2 years
    @Steve Smith The output is: Tue Sep 14 14:17:16 2021
  • Howard Hinnant
    Howard Hinnant almost 2 years
    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.