Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ How to convert date from input (string year, string month, string day) to time_point

Tags:

c++

time

My teacher said that i have to convert the file with lines like that:

Jan Kowalski 1997 4 3

to class person with pools like:

string name, surname;
std::chrono::system_clock::time_point dateofbirth;

How can i create time point from 3 integers? I suppose it is not the easiest way to store that kind of data.

"A reference to a specific point in time, like one's birthday, today's dawn, or when the next train passes. In this library, objects of the time_point class template express this by using a duration relative to an epoch (which is a fixed point in time common to all time_point objects using the same clock)."

But how do i make duration from those data?

I suppose i should start with something like:

using std::chrono::system_clock;
system_clock::time_point today = system_clock::now();
std::chrono::duration<int, std::ratio<60 * 60 * 24> > one_day;
like image 921
Michał Dadej Avatar asked Jan 05 '23 23:01

Michał Dadej


1 Answers

You can start by storing the birth date in std::tm (http://en.cppreference.com/w/cpp/chrono/c/tm), a structure that holds a date and time broken down into its components. For example:

std::tm tm;
tm.tm_mday = 3;
tm.tm_mon = 4;
tm.tm_year = 1977;

This std::tm structure can be converted to std::time_t (http://en.cppreference.com/w/c/chrono/time_t), which holds the number of seconds since epoch.

std::time_t tt = timegm(&tm);

Which in turn can be used to create the std::chrono::system_clock::time_point you are looking for:

std::chrono::system_clock::time_point dateofbirth = std::chrono::system_clock::from_time_t(tt);
like image 114
Moreira Avatar answered Jan 25 '23 21:01

Moreira