SyncMaster
SyncMaster

Reputation: 9966

compare dates in C++

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.?

Upvotes: 2

Views: 7979

Answers (5)

Satbir
Satbir

Reputation: 6506

Parse values, use std::mktime function to get time_t and now use std::difftime to get the difference.

Upvotes: 4

dtw
dtw

Reputation: 1815

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

Upvotes: 2

AndersK
AndersK

Reputation: 36092

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.

Upvotes: 0

Test
Test

Reputation: 1727

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.

Upvotes: 1

iamMobile
iamMobile

Reputation: 969

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

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

Upvotes: -2

Related Questions