Solved

Dates in C++

Posted on 2013-11-18
3
252 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 34

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 34

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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
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.

689 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