Solved

Dates in C++

Posted on 2013-11-18
3
234 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 33

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 33

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

948 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