Get current date and time ?

How can i make the console return the exact date and time from the system ?
1
2
3
4
5
6
7
8
9
10
11
12
#include <ctime>
#include <iostream>
using namespace std;

int main() {
    time_t t = time(0);   // get time now
    struct tm * now = localtime( & t );
    cout << (now->tm_year + 1900) << '-' 
         << (now->tm_mon + 1) << '-'
         <<  now->tm_mday
         << endl;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;

string monthString[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
string dayString[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };

//======================================================================

void getTm( int &year, int &month, int &day, int &hour, int &mins, int &secs, int &weekDay )
{
   time_t tt;
   time( &tt );
   tm TM = *localtime( &tt );

   year    = TM.tm_year + 1900;
   month   = TM.tm_mon ;
   day     = TM.tm_mday;
   hour    = TM.tm_hour;
   mins    = TM.tm_min ;
   secs    = TM.tm_sec ;
   weekDay = TM.tm_wday ;
}


//======================================================================


int main()
{
   int year, month, day, hour, mins, secs, weekDay;
   getTm( year, month, day, hour, mins, secs, weekDay );

   cout << "Date: " << dayString[weekDay] << ", " << day << " " << monthString[month] << " " << year << '\n';

   #define SP << setfill( '0' ) << setw( 2 ) <<
   cout << "Time: " SP hour << ":" SP mins << "." SP secs << '\n';
}


//====================================================================== 

Date: Friday, 15 December 2017
Time: 13:19.33

Topic archived. No new replies allowed.