tags:

views:

377

answers:

5

Hi, i have a file, 'date.txt' which has date in it. Like, Mon Oct 13 09:37:08 2009.

Now i want to compare this date with system date. How can i compare dates in C++.?

I used this code to get the contents from the file 'date.txt'

    string date;
    while ( inDateFile >>date) //inDateFile is an ifstream object 
           cout<<date<<endl;

And this code to get system date,

  time_t timer;
  struct tm *tblock;
  timer = time(NULL);
  tblock = localtime(&timer);
  string str = asctime(tblock);

Now how can i compare these two dates.?

A: 

http://datetime.perl.org/index.cgi?FAQBasicUsage

You will have to convert your date from txt file to tm structre before you compare.

iamiPhone
@iamiPhone , i think solution is expected in c++
sat
ya. how can i do in C++.?
pragadheesh
+1  A: 

convert the date string to a numeric time value (32 or 64 bits), aka, make time, then compare to the system time which time(NULL) returned.

EffoStaff Effo
man strptime/mktime
EffoStaff Effo
Yeah, don't bother converting the current date to a string. It won't give you much. Besides storing the data.txt info as "time" will make it easier to manipulate later.
baash05
+2  A: 

parse values,use mktime function to get time_t & now use difftime to get the difference.

sat
A: 

if you want to just parse the string in your file you need to split up the string in the resp values, you also probably need to check what country region to take that into account since different regions have different order/month names etc. You could make that configurable in which order the different tokens appear in your text.

One way to solve this is by for instance take your string 'date' and then use the template Tokenizer from boost (or if you want to do it the C way call the strtok() function) to split up the string into substrings depending on delimiters. After that it is easy to convert the input.

Another maybe simpler way is when you read from the file instead of reading the whole string read up to a delimiter e.g. ',' then read again - you can use inDateFile.getline() for that.

Anders K.
+1  A: 

We use boost date_time for reading dates from strings and then comparing them. It works very well in our experience.

dtw