Search code examples
c++datetimedigitsctime

C++ current time -> two digits


I display the current date/time via

#include <ctime>
time_t sec = time(NULL);
tm* curTime = localtime(&sec);    
cout << "Date: " <<  curTime->tm_mday << "." << curTime->tm_mon << "." << curTime->tm_year+1900 << endl;
cout << "Time: " << curTime->tm_hour << ":" << curTime->tm_min << ":" << curTime->tm_sec << endl;

Actually it displays e.g.

Date: 4.10.2016
Time: 9:54:0

I got 2 problems here:

  1. I want two digits for both, the date (day and month) and the time (hour, minute and second). So it should display 04.10.2016 and 09:54:00
  2. Today, it displays 24.10.2016 but today it's the 24.11.2016. Why does it display october and not november? The Linux-clock shows the time correctly.

Thanks for all your help :)


Solution

    1. You should use manipulators for printing. in printf("%02d", curTime->tm_hour) in cout, you can use, std::cout << std::setw(2) << std::setfill('0') << curTime->tm_hour.

    2. tm_mon is from 0 to 11. So you should use tm_mon+1 for printing.