In my c++ project about an Airline Reservation System, I have a class member variable for the date stored as a string (i.e. "4/20/2022") and now I need to store the time as well so I added ctime library. The problem is I cannot compare them because the ctime structure for date&time gives the date as separate member variables.
Is there a way to compare them?
Here is an example:
time_t ko = time(nullptr);
struct tm time_date_struct = *localtime(&ko);
struct destination_structure {
int offer_id,seat[size];
std::string departure;//store time
std::string arrival;//store time
std::string from_day; // date as string (4/20/2022)
std::string to_day; // date as string (4/21/2022)
destination_structure* next;
};
//...
if(current->from_day < time_date_struct && current->to_day && current->departure < time_date_struct.tm_hour) {
//...
}
update compile this sample
<chrono>, see the bottom half of this answer.First, there's no structure named
ctime. You were describingstd::tm.To create a
std::tmfrom given values(year, month, day), you would do something like:This would assign year, month, and day correspondingly, while keeping the hour, minute, second as 0. Note that you need to minus a number for year and month, because
std::tmuses 1900 as the base year, and January as the base month.Similarly, you can assign hour/min/sec to
calendar_timewith.tm_hour/.tm_min/.tm_sec.However,
std::tmcan't be used to compare with anotherstd::tm. Instead, you would need to first convert them into astd::time_t:Now you can compare the time you create with current time:
Demo: https://godbolt.org/z/vocGM4WE8
Alternatively, you can format a string from
std::timewith the help ofstd::put_time:This would create a string in the format of
mm/dd/yyyy. Now you can do a string comparison between this and other strings. However, this is not recommended, as this could easily fail if your strings are not formatted in the exact same way(which will be a problem in your case, since you stored the date as4/20/2022instead of04/20/2022).Demo: https://godbolt.org/z/bz36TPfzq
C++20
<chrono>With the
<chrono>library, creating a date/time object became really simple :That's all you need!
Demo: https://godbolt.org/z/bMzv9crxh
And you can easily add the time to the date as well:
Sad news is not all compilers fully supports the c++20
<chrono>yet. A workaround is to use thedatelibrary, written by the same author of<chrono>, for now.Demo: https://godbolt.org/z/sWzo5GrE1