ctime header syntax

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <ctime>

int main ()
{
    const std::time_t rawtime = std::time(nullptr) ; // current time

    const tm timeinfo = *std::localtime( std::addressof(rawtime) ); // convert to calendar time

    const int day = timeinfo.tm_mday;
    const int month = timeinfo.tm_mon + 1 ; // we want january == 1 etc.
    const int year = timeinfo.tm_year + 1900 ;

    std::cout << "day " << day << "  month " << month << "  year " << year << '\n' ;
}
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 ?
C++20: Calendar https://en.cppreference.com/w/cpp/chrono#Calendar

For this simple use case, I find it easier to use <ctime>
Topic archived. No new replies allowed.