hi all , im trying to compare two time values , but im unable to display the correct result , the retval returns -1 for both d1 and d2 , i suppose the mktime is the convert the values into seconds since EPOCH . any idea as to where im wrong ?

#include <sys/time.h>
#include <time.h>
#include <stdlib.h>
#include <iostream.h>
time_t to_seconds(const char *time)
{
        struct tm storage={0,0,0,0,0,0,0,0,0};
        char *p=NULL;
        time_t retval=0;
        p= (char *)strptime(time,"%H:%M",&storage);
        if(p==NULL)
        {
                retval=0;
        }
        else
        {
                retval=time(&storage);
        }       
        return retval;
}
int main(void)
{
   
   
   
   char *stoptime="01:05";
   char *currenttime="15:15";

   time_t d1=to_seconds(stoptime);
   time_t d2=to_seconds(currenttime);

   cout<<"time comparison:<<stoptime<<currenttime;
  
   
   if(d2>d1)
   {  
     cout<<"currentdate is larger\n";
   }
   if(d2<=d1)
   {
     cout<<"currentdate is smaller\n";
   
   }
}

1. You can't compile (and especially run) this snippet: the time library function has time_t* parameter, not struct tm*.
2. Use mktime instead of time
3. The time_t value is not seconds after epoch but you can compare these values.

hey , thanks , i did notice that and changed it to 'mktime' , but it still returns -1 :(

The tm::tm_year member defines year-1900 value. Therefore you initialize struct tm object as a moment in year 1900. However time_t epoch started in midnight of January 1 year 1970. Yet another bad value: tm_mday member must be 1..31 but not 0. That's why mktime can't convert year 1900 day (and zero day of month) in a time_t value and returns -1.

Correction: obvious (force a year >= 1970 and <= 2038, for example, set tm_year to 109 + provide non-zero tm_mday member). In other words, provide correct argument value for mktime...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.