Solved

Dates in C++

Posted on 2013-11-18
3
227 Views
Last Modified: 2013-11-18
Hi

I'm looking at writing a small program that needs a user to input a date e.g.

cin >> myDate;

which will be in the format 12/11/2013 (dd/mm/YY)

What is the best way to do this in C++ (cross platform).

Finally, if two dates are input, I need to work out the number of days between the two dates.

I've done the usual googling and it all seems fairly complex! What I can't understand that there isn't a standard library that would do this. Using Python, for example, is a breeze! Why is it so complicated in C++?

Am I missing something?

Josh
0
Comment
Question by:IssacJones
  • 2
3 Comments
 
LVL 32

Accepted Solution

by:
sarabande earned 300 total points
ID: 39656529
you can use a little class like the following:

#include <time.h>
#include <string>
#include <sstream>

class simpledate
{
      int idate;
public:
      simpledate(int dt) : idate(dt) {}
      simpledate(int d, int m, int y) : idate(y*10000+m*100+d) {}
      simpledate(const char * szdate) : idate(0)
      {
          std::istringstream iss(szdate);
          int d, m, y;
          char sep;
          if (iss >> d >> sep >> m >> sep >> y)
          {
                idate = y*10000+m*100+d;
          }      
      }
      void to_tm(struct tm & t) const
      {
           int d, m, y;
           d = idate%100;
           m = (idate%10000)/100;
           y = idate/10000;
           memset(&t, 0, sizeof(struct tm));
           t.tm_year = (y > 1900)? y-1900 : y + 100;
           t.tm_mon = m-1;
           t.tm_mday = d;
      }
      bool isvalid() const
      {
           struct tm t = { 0 };
           to_tm(t); 
           time_t tt = mktime(&t);
           return (tt == time_t(-1))? false : true;
     }
     bool datediff(const simpledate & sd, int & diff) const
     {
           if (!isvalid() || !sd.isvalid())
               return false;           
           struct tm t1 = { 0 };
           to_tm(t1); 

           struct tm t2 = { 0 };
           sd.to_tm(t2); 
           
           time_t tt1, tt2;
           tt1 = mktime(&t1);
           tt2 = mktime(&t2);
           diff = (int)(tt2 - tt1)/(24*60*60);
           return true;
     }
};

Open in new window



you could use the class by reading the dates int std::string variables (for example sdate1, sdate2) using std::getline().

then create simpledate object by passing sdate1.cstr(). same for the 2nd date. then you could use the datediff member of either of the dates.

note, in mfc there are classes CTime and CTimeDiff which do a similar job.
Sara
0
 

Author Comment

by:IssacJones
ID: 39656999
Hi Sara

Thank you for your excellent response. However, can you tell me why no standard class was included with C++ which dealt with dates and times? As these are fundamental to most business uses I would have thought a library would have been created. I'm puzzled why it does not appear to exist.

Josh
0
 
LVL 32

Expert Comment

by:sarabande
ID: 39657181
dates and times are not easy. you have to consider different time zones, different formatting, day-light-savings, leap years, milliseconds, past times, future times, working-days, holidays, names for months, ...

for example, you want to input only two digits for the year what rises up to decide between years of the last century (as you would assume if the date is a birth date) or current and future dates.

actually every project i was involved in, had some kind of a date/time class/structure and appropriate members. it is not so difficult as long as you have homogenous (comparable) dates and only a few requirements on them, but could turn to very complex code if not.

note, for the simpledate class you may overload

std::istream operator>>(std::istream & is, simpledate & sd)
{
      int d, m, y;
      char sep;
      if (is >> d >> sep >> m >> sep >> y)
      {
           int idate = y*10000+m*100+d;
           sd = simpledate(idate);
      }
      return is;
}

Open in new window


what would allow to use

simpledate dt;
cin >> dt;

Open in new window


the problem with that code is that it would set the cin to fail state if the integer conversion fails because of wrong input. that could make your input hang or prevents from further input as long as you do not clear the fail bit and reset the cin stream. therefore, it is much easier to read a string with getline and then use the constructor of the date class to do the conversion.

Sara
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now