Folks, i need a help with ctime functions syntax.
How should i amend below code to get proper data?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include <stdio.h> /* puts, printf */
#include <ctime>
#include <iostream> /* time_t, struct tm, time, localtime */
using namespace std;
int main ()
{
int hours, minutes, seconds, days, month, years;
time_t rawtime;
struct tm timeinfo;
time (&rawtime);
cout << rawtime << endl;
days = timeinfo.tm_mday;
month = timeinfo.tm_mon;
years = timeinfo.tm_year;
cout << "struct tm from timeinfo" << endl;
cout << "days " << days << "month " << month << "years " << years << endl;
}
|
Last edited on
Perhaps:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include <ctime>
#include <iostream>
int main() {
time_t rawtime;
time(&rawtime);
std::cout << rawtime << '\n';
const auto timeinfo {localtime(&rawtime)};
const auto days {timeinfo->tm_mday};
const auto month {timeinfo->tm_mon};
const auto years {timeinfo->tm_year};
std::cout << "struct tm from timeinfo\n";
std::cout << "days " << days << ", month " << month << ", years " << years <<'\n';
}
|
You need a function such as localtime() to populate the tm structure.
See
http://www.cplusplus.com/reference/ctime/localtime/
Also note what the values of tm mean. See
http://www.cplusplus.com/reference/ctime/tm/
Last edited on
Thanks, guys!
Please advise on below:
If I divide 1640604592 / 60 / 60 / 24 / 365 = 52. Why it counts 121? if starting point 1 January 1970 still can not get the logic :)
The year starts at 1900. So 121 + 1900 = 2021 as expected. See the second of my links above.
@sseplus, @JLBorges,
isn't there a way to do this with std::chrono in C++17 / C++20 ?