17

How to get current date d/m/y. I need that they have 3 different variables not one, for example day=d; month=m; year=y;.

unwind
  • 391,730
  • 64
  • 469
  • 606
Wizard
  • 10,985
  • 38
  • 91
  • 165

3 Answers3

29

For linux, you would use the 'localtime' function.

#include <time.h>

time_t theTime = time(NULL);
struct tm *aTime = localtime(&theTime);

int day = aTime->tm_mday;
int month = aTime->tm_mon + 1; // Month is 0 - 11, add 1 to get a jan-dec 1-12 concept
int year = aTime->tm_year + 1900; // Year is # years since 1900
Anya Shenanigans
  • 91,618
  • 3
  • 107
  • 122
17

Here is the chrono way (C++0x) - see it live on http://ideone.com/yFm9P

#include <chrono>
#include <ctime>
#include <iostream>

using namespace std;

typedef std::chrono::system_clock Clock;

int main()
{
    auto now = Clock::now();
    std::time_t now_c = Clock::to_time_t(now);
    struct tm *parts = std::localtime(&now_c);

    std::cout << 1900 + parts->tm_year  << std::endl;
    std::cout << 1    + parts->tm_mon   << std::endl;
    std::cout <<        parts->tm_mday  << std::endl;

    return 0;
}
sehe
  • 374,641
  • 47
  • 450
  • 633
2

The ctime library provide such functionnality.

Also check this. It is an other post that might help you out depending on your platform.

Community
  • 1
  • 1
TurnsCoffeeIntoScripts
  • 3,868
  • 8
  • 41
  • 46
  • 1
    `#include #include 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; } ` Thanks – Wizard Dec 01 '11 at 15:34