Get Date in C++ and check if expired

Hello,

how I can get the currrent date and compare with a special one if exoired?
Maybe with a integer.
Sample: I have 20100416 and want to check whether this date expired.

Thanks,

Ocrana
OcranaAsked:
Who is Participating?
 
phoffricConnect With a Mentor Commented:
In your post you didn't mention whether your date was GMT or local time. If local time, then you can use the localtime function, format it to look like a string of the form "YYYYMMDD", and then compare strings.

string getCurrentLocalDate() {
    // convert local time to string of form "YYYYMMDD"
    time_t rawtime;
    struct tm * timeinfo;
    char buffer[10];

    time ( &rawtime );
    timeinfo = localtime( &rawtime );
    strftime(buffer, sizeof(buffer), "%Y%m%d", timeinfo);
    return buffer;
}

bool isExpired(string dueDate) {
    string todaysDate = getCurrentLocalDate() ;
    return (todaysDate > dueDate) ? true : false;
}

Open in new window

0
 
cupCommented:
You can get the current date with

time_t now = time (0);
tm nowtm = *(gmtime (&now));

The easiest way, if you have the dates in yyyymmdd format is

int today = nowtm.tm_year * 10000 + (nowtm.tm_mon + 1) * 100 + nowtm.tm_mday;

You can then compare today with your expiry date.  Since you have stored it as yyyymmdd, it will be numerically less if it has expired.

The alternative is to convert your expiry date to a number using mktime - see http://www.cplusplus.com/reference/clibrary/ctime/mktime/
0
 
Infinity08Commented:
Comparing times is easiest with difftime :

        http://cplusplus.com/reference/clibrary/ctime/difftime/

Just get two time_t values for the times you want to compare (see cup's post http:#30281691), and call difftime.
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
habeeballahConnect With a Mentor Commented:
phoffric(id: 30285279) above is on the track. My suggestion is to use datatype long instead of strings so as to make it easy and efficient in order to compare.

so phoffric's functions would become as follows:

long getCurrentLocalDate()
{
    time_t rawtime;
    struct tm * timeinfo;
    char buffer[10];
    long lbuff;
    time ( &rawtime );
    timeinfo = localtime( &rawtime );
    strftime(buffer, sizeof(buffer), "%Y%m%d", timeinfo);
    lbuff=atol(buffer);
    return lbuff;
}

bool isExpired(long dueDate)
{
    long currdt = getCurrentLocalDate() ;
    return (currdt > dueDate) ? true : false;
}

Then to use it wherever you want to check for expiry of the date with the current date, say

    if(isExpired(20100411)==false)
        cout<<"not expired"<<endl;
    else
        cout<<"expired"<<endl;

Note: if you accept this solution, you are suppose to split points to phoffric too.

0
 
itsmeandnobodyelseCommented:
In C++ it is quite handy to use a date or date-time class for the functionality posted above.

Then you could do like

   DateTime dt(2010, 4, 16);
   DateTime today(DT_TODAY);
   if (dt < today)
       cout << "time expired" << endl;


The above would require only little code (see below) and easily could be enhanced to more (e. g. calculate datetime differences of various time units or count only working days and so on).
enum DateTimeSpec { DT_NOW, DT_TODAY };

class DateTime
{
   int dat;
   int tim;
public:
   DateTime(int d = 0, int t = 0)  dat(d), tim(t) {}
   DateTime(int y, int m, int d, int h = 0, int i = 0, int s = 0)  
   {
      dat = y*10000+m*100+d;
      tim = h*10000+i*100+s;
   }
   DateTime(DateTimeSpec dts)  dat(0), tim(0) 
   {
      time_t tt = time(0);
      struct tm * ptm = localtime(&tt);
      switch (dts)
      {
         case DT_NOW: tim = ptm->tm_hour*10000+ ptm->tm_min*100 + ptm->tm_sec;
              // the missing break is intended
         case DT_TODAY: dat = ptm->tm_year*10000+(ptm->tm_mon+1)*100+ptm->tm_mday; 
              break;
      }
   }
   bool operator<(const DateTime & dt) { return dat < dt.dat || (dat == dt.dat && tim < dt.tim); }
};

Open in new window

0
 
itsmeandnobodyelseCommented:
There is a colon : missing before the initializer list of the constructors:

   DateTime(int d = 0, int t = 0)  : dat(d), tim(t) {}
   DateTime(DateTimeSpec dts)  : dat(0), tim(0) { ... }
0
 
OcranaAuthor Commented:
Both solutions are great but finaly I prefer the numeric way. This I w split the points.  Many thanks.
0
 
Infinity08Commented:
lol ... may the most unnecessarily complicated solution win.
0
 
phoffricCommented:
Initially I asked about whether your string date was GMT or local time. If you run into any timezone issues, then the following thread may help.
      http://w.e-e.com/lmvF1T
0
 
cupCommented:
Interesting how many people still store dates with the leading 20.  Unless you're dealing with dates which also have a leading 19,  it might be better to drop the 20.

One minor point that is sometimes missed : tm_year is from 1900 so you ought to add 1900 or subtract 100  before multiplying by 10000.
0
 
phoffricCommented:
>> still store dates with the leading 20
I never did until the Y2K crisis. Then we were told from now on its YYYY
Now we'll avert the Y2100 crisis
Of course, as you know, the time.h functions currently has a Y2038 crisis.
0
 
itsmeandnobodyelseCommented:
>>>> Unless you're dealing with dates which also have a leading 19,  

Actually I am dealing only with dates less than 2000, cause I currently run a huge persons database were most people were older than 10 years ...

>>>> I never did until the Y2K crisis

I never stored a date other than as YYYYMMDD since 1981 when I started to make my first database. Therefore no crisis.  


>>>> tm_year is from 1900
That is exactly what I mean. The tm_year is an int. Whoever thought out to make that member from 1900 is responsible for cillions of unnecessary errors like the one I made in that code snippet...
0
 
itsmeandnobodyelseCommented:
>>>> I never stored a date other than as YYYYMMDD since 1981

It is not quite true. When I experienced with bitfields I stored the year with 6 bits. The goal was to store a timestamp into a 32-bit integer. It was good encapsulated so it doesn't actually count ;-)
0
 
phoffricCommented:
>> tm_year is from 1900 so you ought to add 1900
The time.h has some strange rules. year is offset from 1900, yet seconds are returned as number since epoch (jan 1, 1970). Day in month starts at 1 but month in year starts at 0. Why did they do that - a committee?
0
 
cupCommented:
With time_t, have you ever tried negative numbers: it goes backwards from 1970 to 31Dec1969.
0
All Courses

From novice to tech pro — start learning today.