Solved

Dates in C++

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
C language IDE – Compilers installation 14 88
C++ to C# code conversion issue 4 126
C++ help/ Toy problem 19 69
Gaming Software 1 37
Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
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 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.

738 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