-2

I am using C on Unix. The program displays the time and I am trying to figure out how to offset the current time in minutes and hours.

This part of the code

  while ( ( let = getopt(argc, argv, "alo:vh")) != -1 ) {
    switch (let) {
    case 'o':  offset = atoi(optarg);  break; }

and later in this part:

void clock(int sig, int time_expires)
{
time_t       now;
struct tm   *dateinfo; 

(void) time(&now);
now = now + offset;

dateinfo = localtime( &now ); }

Makes an -o offset, which offsets the current time by a certain amount of seconds. For example, -o590 would offset the current time by 590 seconds.

I am trying to figure out how to do this same thing only with an -h flag that offsets the time by a certain amount of hours (like -h6 offsets the time by 6 hours) or by a -m flag which offsets the time by minutes.

I have tried dividing the current -o flag by 60 or 360 but that is not working. Can anyone point me in the right directions here?

Meg
  • 7
  • 2
  • 1
    "I have tried dividing the current -o flag by 60 or 360 but that is not working". Please be more specific. Show the exact code you have tried and describe in what way it is "not working". – kaylum Nov 04 '15 at 02:26
  • 2
    The default ofset is in seconds. Why divide? You should be multiplying by 60 for minutes and 3600 for hour. So `-m1` is actually equivalent to `-o60` and `-h1` is `-o3600`. – alvits Nov 04 '15 at 02:31

2 Answers2

1

To change time_t by so many hours, minutes, seconds in a portable fashion without relying on time_t is some integer type of seconds since 1970, use mktime()

time_t adjust(time_t t, int hour, int minute, int second) {
  struct tm *dateinfo; 
  dateinfo = localtime(&t);
  if (dateinfo == NULL) return (time_t) -1;
  dateinfo->tm_hour += hour;
  dateinfo->tm_min += minute;
  dateinfo->tm_sec += second;
  return mktime(dateinfo);
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

The time_t structure defines the number of seconds since Jan 1, 1970 UTC.

If you want to add n minutes you should do:

now+= n*60

And for n hours you should:

now+= n*3600

Alternatively you can use struct tm and access directly to the time quanta you wish to modify.

struct tm {
   int tm_sec;         /* seconds,  range 0 to 59          */
   int tm_min;         /* minutes, range 0 to 59           */
   int tm_hour;        /* hours, range 0 to 23             */
   int tm_mday;        /* day of the month, range 1 to 31  */
   int tm_mon;         /* month, range 0 to 11             */
   int tm_year;        /* The number of years since 1900   */
   int tm_wday;        /* day of the week, range 0 to 6    */
   int tm_yday;        /* day in the year, range 0 to 365  */
   int tm_isdst;       /* daylight saving time             */
};
PeCosta
  • 537
  • 4
  • 13