Link to home
Start Free TrialLog in
Avatar of oleber
oleberFlag for Portugal

asked on

timelocal

I have a Date in "yyyymmdd" and I need to add or remove a amount of time.

I'm a perl programmer and in perl I can use timelocal method to convert a date array (+- struct tm) in time_t structure make the calculation and after that I use localtime to reconvert the date to the format I need (+- struct tm).

Is there a way of doing this in C/C++?
Did someone did that?

There is a better way of doing it?
Avatar of jmccay
jmccay

All the functions you need should be in the "time.h" header file.  time() will return a time_t of the current date and time, and ctime will convert it back.  If you need more I suggest looking these functions up.
   If you are using Visual Studio, look up CTime and CTimeSpan.  Hope this helps.
Avatar of oleber

ASKER

The code I'm trying to do is something like

  string str("20010405"); /* Come from a DB Query */
  struct tm myTime;
  myTime.tm_sec = 0;
  myTime.tm_min = 0;
  myTime.tm_hour = 0;
  myTime.tm_mday = atoi(str.substr(6,2).c_str());
  myTime.tm_mon = atoi(str.substr(4,2).c_str());
  myTime.tm_year = atoi(str.substr(0,4).c_str());
  time_t t = timelocal(myTime);
  t += 60*60*24*nDays;
  struct tm* pTime = localtime(t);
  char sResult[9];
  sprintf(sResult,"%.04d%.02d%.02d", pTime->tm_year, pTime->tm_mon, pTime->tm_mday);
  printf("Result date: %s",sResult);

So I need the timelocal method. My work have to work in Windows and Unix (Sun Machine) so I'm working just with ANSI C/C++
ASKER CERTIFIED SOLUTION
Avatar of jmccay
jmccay

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I had a mistake.  The follow:

" I should note that the time functions only use a long to hong the time and the base time on windows
is Jan 1, 1970 00:00:00 and the maximum time it can represent is Jan 18, 2038 19:14:07."

should be:
" I should note that the time functions only use a long to hold the time. The base time on windows
is Jan 1, 1970 00:00:00 (24 hour) and the maximum time it can represent is Jan 18, 2038 19:14:07."