2

So, I want to do a class Delivery like this:

class Delivery{
private:
    string recipient;
    time_t date;
}

So, the date is time_t. The thing I want to do is let the user type the delivery date. Maybe the delivery is made today, maybe tomorrow, maybe next month. I could've made the date attribute string date instead of time_t. Why I didn't do that? Because, I have a list of deliveries and I want to sort the deliveries and then to print the deliveries that were made in a certain period. For example, print the deliveries made from 12.03.2013 until 25.08.2013.

The question is: how can I let the user set the date? I searched the Internet but I didn't found any useful functions. Is there a way to solve this problem?

mmmmmm
  • 31,464
  • 27
  • 87
  • 113
MathMe
  • 101
  • 5
  • 13
  • 1
    [boost.Date_time](http://www.boost.org/doc/libs/release/doc/html/date_time.html) may be suitable. – Cubbi May 27 '13 at 15:18
  • possible duplicate of [How to convert a string variable containing time to time\_t type in c++?](http://stackoverflow.com/questions/11213326/how-to-convert-a-string-variable-containing-time-to-time-t-type-in-c) – user93353 May 27 '13 at 15:19

3 Answers3

1

Assuming you read the input into a string named time_string in the format 01/01/13:

struct tm tm;
strptime(time_string, "%D", &tm);
time_t t = mktime(&tm);

If you include the full year, e.g. 01/01/2013, replace strptime(time_string, "%D", &tm); with strptime(time_string, "%m/%d/%Y", &tm);. %m is the month, %d the day, and %Y the full year, e.g. 2013 instead of 13. Also note that if time_string is an std::string instead of a C-style string, you need to replace time_string with time_string.c_str() in the call to strptime.

Sources: https://stackoverflow.com/a/11213640/2097780 and http://publib.boulder.ibm.com/infocenter/zos/v1r12/index.jsp?topic=%2Fcom.ibm.zos.r12.bpxbd00%2Fstrptip.htm.

Community
  • 1
  • 1
kirbyfan64sos
  • 9,791
  • 6
  • 54
  • 73
0

Working on date/time involves using the struct tm and time_t data structures.

To convert time_t to struct tm, there are a few differnt functions, such as localtime(), gmtime(), etc.

To convert from struct tm to time_t, you use mktime().

Obviously, you'll also need to write some code that reads year, month, day and perhaps hours and minutes from the user as integer values, then fill in a struct tm with the relevant values, and call mktime() to convert it to "seconds since 1 jan 1970" in a time_t value.

All functions to do this are declared in <ctime>

Mats Petersson
  • 123,518
  • 13
  • 127
  • 216
0

Given that you are using C++, you might want to consider using: Boost DateTime.

doron
  • 26,460
  • 11
  • 62
  • 99