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;
.
Asked
Active
Viewed 7.7k times
17
-
What have you tried? http://stackoverflow.com/questions/997946/c-get-current-time-and-date – daniloquio Dec 01 '11 at 15:20
-
@Fredrik, it's simpler to ask than do research. – Marius Bancila Feb 01 '13 at 11:03
3 Answers
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
-
-
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 – Anya Shenanigans Feb 01 '13 at 11:01
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
-
1
-
@PaoloM that header is required for [`std::time_t`](http://en.cppreference.com/w/cpp/chrono/c/time_t) – sehe Sep 10 '15 at 12:36
-
Sorry, under gcc 4.8 it compiles without `
`. It gets included by ` – Paolo M Sep 10 '15 at 12:43` for sure.
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 – Wizard Dec 01 '11 at 15:34using 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