16

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
  • 378,987
  • 63
  • 458
  • 590
Wizard
  • 10,467
  • 37
  • 86
  • 159

3 Answers3

28

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
Petesh
  • 87,225
  • 3
  • 99
  • 116
  • Did you mean localtime(&time(NULL)); ? – maximus Feb 01 '13 at 02:53
  • I corrected the answer as it would not compile as-is. You can't an rvalue by pointer (i.e. just a number) so you need to put it into a variable first – Petesh Feb 01 '13 at 11:01
16

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
  • 350,152
  • 45
  • 431
  • 590
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,750
  • 8
  • 38
  • 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