?
Solved

Dates in C++

Posted on 2013-11-18
3
Medium Priority
?
254 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 35

Accepted Solution

by:
sarabande earned 1200 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 35

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

Enroll in August's Course of the Month

August's CompTIA IT Fundamentals course includes 19 hours of basic computer principle modules and prepares you for the certification exam. It's free for Premium Members, Team Accounts, and Qualified Experts!

Question has a verified solution.

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

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
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.

764 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