math with ctime and time_t

4.4k views Asked by At

Does anyone know how todo math with ctime? I need to be able to get the time in sec in "time_t" (like it normally does) and then subtract a set number of seconds from it before inputting time_t into ctime to get the time and date.

so basically it would calculating the date of so many sec ago.

3

There are 3 answers

0
deeiip On

You can try:

time_t now = time( NULL);
struct tm now_tm = *localtime( &now);
now_tm.tm_sec -= 50;   // subtract 50 seconds to the time
now_tm.tm_sec +=1000;  // add 1000 sec to the time
printf( "%s\n", asctime( &now_tm));
2
SoapBox On

time_t is an integral type. It always represents a number of seconds, so you can freely add/subtract integers from it.

Example:

time_t now = time(nullptr);
time_t one_minute_ago = now - 60;
std::cout << ctime(&one_minute_ago) << std::endl;
0
pang1567 On

time_t The most basic representation of a date and time is the type time_t. The value of a time_t variable is the number of seconds since January 1, 1970, sometimes call the Unix epoch. This is the best way to internally represent the start and end times for an event because it is easy to compare these values. struct tm While time_t represents a date and time as a single number, struct tm represents it as a struct with a lot of numbers:

struct tm
{
  int tm_sec;            /* Seconds.    [0-60] (1 leap second) */
  int tm_min;            /* Minutes.    [0-59] */
  int tm_hour;            /* Hours.    [0-23] */
  int tm_mday;            /* Day.        [1-31] */
  int tm_mon;            /* Month.    [0-11] */
  int tm_year;            /* Year    - 1900.  */
  int tm_wday;            /* Day of week.    [0-6] */
  int tm_yday;            /* Days in year.[0-365]    */
  int tm_isdst;            /* DST.        [-1/0/1]*/
};

Conversion You can convert a time_t value to a struct tm value using the localtime function:

struct tm startTM;
    time_t start;

    /* ... */

    startTM = *localtime(&start);

So,you can subtract subtract a set number of seconds like this

startTm.tm_sec -= somesecond;

add convert to time_t like this

struct tm startTM;
    time_t start;

    /* ... */

    start = mktime(&startTM);

and use ctime fun to convert date

ctime(&start)

hope it can helpful!