BWMustang13 BWMustang13 - 1 year ago 379
C++ Question

How do I get the current date in C++?

I have been trying to get the current date in C++ for a while now and I cannot figure out what I am doing wrong. I have looked at several sites and all of the solutions that I implement I get an error that says, “This function or variable may be unsafe. Consider using localtime_s instead.” I tried several of the solutions found here (including the one below) but I could not get any of them to work. What am I doing wrong?

#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>

using namespace std;

int main()

const int SALARY = 18;
const int COMMISSION = .08;
const int BONUS = .03;

int monthlySales;
int appointmentNumber;

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

string name;

//this is where the user adds their name and date
cout << "Please enter the sales representative's name: ";
cin >> name;
cout << "Please enter the number of appointments: ";
cin >> appointmentNumber;
cout << "Please enter the amount of sales for the month: $";
cin >> monthlySales;

//clear screen and execute code

cout << setfill(' ');
cout << "Sales Representative:" << name << endl;
cout << "Pay Date:" << (now->tm_mon + 1) << " " << now->tm_mday << " " << (now->tm_year + 1900) << endl;
cout << "Work Count:" << appointmentNumber << "Sale Amount"
<< monthlySales << endl;


return 0;

Answer Source

You can try below code and description beneath it.

#include <iostream>
#include <ctime>

int main ()
  time_t rawtime;
  struct tm * timeinfo;
  char buffer[80];

  time (&rawtime);
  timeinfo = localtime(&rawtime);

  strftime(buffer,80,"%d-%m-%Y %I:%M:%S",timeinfo);
  std::string str(buffer);

  std::cout << str;

  return 0;


time_t time (time_t* timer);

function returns this value, and if the argument is not a null pointer, it also sets this value to the object pointed by timer.


  • timer Pointer to an object of type time_t, where the time value is can also pass it null pointer in case not required

Return Value

The current calendar time as a time_t object.If the function could not retrieve the calendar time, it returns a value of -1.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download