c++ get current date code example

Example 1: get current date in c++

#include <ctime>
#include <iostream>

int main() {
    std::time_t t = std::time(0);   // get time now
    std::tm* now = std::localtime(&t);
    std::cout << (now->tm_year + 1900) << '-' 
         << (now->tm_mon + 1) << '-'
         <<  now->tm_mday
         << "\n";
}

Example 2: how to get current time in c++

//Simplest way to add time using ctime
	#include <ctime>

	time_t tt;
    time( &tt );
    tm TM = *localtime( &tt );

	//Must add 1 to month and 1900 to the year
    int month=TM.tm_mon+1;
    int day=TM.tm_mday;
    int year=TM.tm_year+1900;

Example 3: c++ get system date

#include <string>
#include <sstream>
#include <iostream>

time_t t = time(0);   // get time now
struct tm * now = localtime( & t );

ostringstream osTime;
osTime << (now->tm_year + 1900) <<
   (now->tm_mon + 1) <<
   now->tm_mday <<
   "\n";

cout << osTime.str();

Tags:

Cpp Example