Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Encountered A Problem

Status
Not open for further replies.

HeIpMe

Programmer
Oct 29, 2003
1
US
Hey I'm Workin on a program that calculates age. My Problem is that I need to access the computer time and somehow compare it to the birthdate input. I tryed to use ctime, but it doesnt work the way i need it to.
ex:

the user inputs a b-date: 08/23/1943
the program has to calculate the date using the computers time. ctime gives me Wed Oct 29 21:03:27 2003. is there a way to convert 08/23/1943 to the ctime format? or the opposite? if anyone can help me that would be greatly appriciated.

MrSmiley
p.s. im not asking for the program i am making it, i just need help on using the computers time
 
There are so many date/time formats... Probably therefore (and by historical reasons) C/C++ includes generic date/time functions only. No standard library function to convert string value to date/time value (see above). It's nothing!
You have two approaches. You may convert the current (computer) time into a string (to compare with user input) or you may convert user input to day/month/year (int) values to compare with current date fields obtained from a library call.
I would rather prepend the 2nd approach. Any user input must be under suspicion (from console ore from file, database etc). Make your program more robust. As minimum you may use old good sscanf:
char userdate[...];
int m, d, y;
if (sscanf(userdate,"%2d/%2d/%4d",&m,&d,&y) == 3)
{
// OK, at least we have 3 ints separated with slash
}
else
{
// Wrong date value!...
}
Get current date by localtime function call:
time_t t = time(0);
struct tm* ptm = localtime(t);
// Now ptm->tm_mday == day today
// ptm->tm_mon+1 == month (tm_mon range is 0..11)
// ptm->tm_year == year
Now you can compare dates as you wish.
Pack this stuff in the function and forget all these details (after testing, of course)...
Good luck!
 
Mr :)

You can not do this using ctime. ctime is defined as the number of seconds elapsed from January 1, 1970, 00:00:00. For this reason, ctime can not represent any date before 1970.
I suggest (if it is Windows) you use the SYSTEMTIME structure. You can get the current date/time using the GetLocalTime API.



Marcel
 
In my post above must be localtime(&t) /* poiter to t */.
MKuiper: why use platform-dependent Windows (or Unix etc) calls? We have language standard library routines and structures in that case.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top