Question

I am trying to write an application for an assignment and I am new to c++. A small portion of the application requires me to store a date and add an arbitrary number of days as an offset from the date. I know how I would accomplish this with Java or C# but I have been unable to find anything for c++. My professor alluded to ctime but after many searches all the examples I found had to do with the current system time. How do I create a ctime::tm struct and set it to an arbitrary date? Is it possible to add a number of days using ctime to obtain another date? For example, if I added 40 days to January 1, 2001 I would expect February 10, 2001 not January 41, 2001.

Was it helpful?

Solution

To be an example of usage

#include <stdio.h>
#include <time.h>

int main ()
{
  time_t currentTime;
  time(&currentTime);  
  struct tm * tmDate;
  int day, month,  year;

  tmDate = localtime (&currentTime);
  tmDate->tm_year = 99;
  tmDate->tm_mon = 11;
  tmDate->tm_mday = 10;

  mktime ( tmDate );

printf("now: %d-%d-%d %d:%d:%d\n", tmDate->tm_year + 1900, tmDate->tm_mon + 1, tmDate->tm_mday, tmDate->tm_hour, tmDate->tm_min, tmDate->tm_sec);

  return 0;
}

as you can see on

  tmDate->tm_year = 99;
  tmDate->tm_mon = 11;
  tmDate->tm_mday = 10;

you can set, sub, add months, years, days .. to date.

For example simply you can add 1 month to date with

  tmDate->tm_mon++;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top