Part_Time_Nerd
Part_Time_Nerd

Reputation: 1014

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
    system("cls");

    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;

        system("pause");

    return 0;
}

Upvotes: 4

Views: 12772

Answers (6)

Howard Hinnant
Howard Hinnant

Reputation: 218750

Here is how I do it:

#include "date/tz.h"
#include <iostream>

int
main()
{
    using namespace std::chrono;
    std::cout << date::make_zoned(date::current_zone(), system_clock::now()) << '\n';
}

which just output for me:

2016-10-18 10:39:10.526768 EDT

I use this C++11/14 portable, free, open-source library. It is thread-safe. It is based on <chrono>. It is type safe and easy to use. If you need more functionality, this library will do it.

  • Get the local time in another timezone
  • Convert local time directly from one timezone to another.
  • Take leap seconds into account in time computations.
  • Stream out / stream in time stamps round trip with any precision, and no loss of information.
  • Search all timezones for a property (such as abbreviation or offset).

This library is being proposed to the C++ standards committee, draft here.

Upvotes: 5

Part_Time_Nerd
Part_Time_Nerd

Reputation: 1014

I greatly appreciate all of your timely the responses. Ultimately I was able to use a variation of Heemanshu Bhalla’s response. I added ‘_CRT_SECURE_NO_WARNINGS’ to the preprocessor definitions by going here then I altered Heemanshu’s code to the following code. This suited my needs.

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

using namespace std;

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

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

    strftime(buffer, 80, "%m/%d/%Y ", timeinfo);
    string str(buffer);

    cout << str << endl;

    system("PAUSE");

    return 0;
}

Upvotes: 0

Heemanshu Bhalla
Heemanshu Bhalla

Reputation: 3765

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;
}

Function

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.

Parameters

  • timer Pointer to an object of type time_t, where the time value is stored.you 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.

Upvotes: 4

perspicuousreading
perspicuousreading

Reputation: 153

This is another way that could work:

time_t current_time;
struct tm *timeinfo;
time(&current_time);
timeinfo = localtime(&current_time);
string date = asctime(timeinfo);

Upvotes: 0

Humam Helfawi
Humam Helfawi

Reputation: 20264

The standard and cross-platform way is to use chrono.

#include <iostream>
#include <chrono>

int main(){
    std::time_t now_time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
    std::cout << "Now:" << std::ctime(&now_time);
}

Upvotes: 1

nishantsingh
nishantsingh

Reputation: 4662

You're getting this warning perhaps because localtime() is not thread-safe. Two instances calling this function might result in some discrepancy.

[...] localtime returns a pointer to a static buffer (std::tm*). Another thread can call the function and the static buffer could be overwritten before the first thread has finished reading the content of the struct std::tm*.

Upvotes: 1

Related Questions