bluefoggy
bluefoggy

Reputation: 1041

Getting a time difference in seconds from now to future using difftime

I am trying to find the difference in seconds from time now and a future time.

#include <time.h>
#include <stdio.h>
#include <float.h>
void main() {

    time_t future = 0xFFFFFFFFFFF;
    time_t now_time = time(NULL);
    printf("The future time is %s\n", ctime(&future));
    long double  diff_in_sec = difftime(time(&future), time(&now_time));
    printf("The diff in sec from now to future is %ld\n", diff_in_sec);
}

Now as i see , difftime returns double even though i try to use long double it is not possible for me to return the proper time diff in seconds. How can i achieve this?

offcourse long double doesn't make any sense there. But i only want to know is there another way i can achieve such a big diff.

Note: I am using 64bit system

Upvotes: 0

Views: 640

Answers (2)

jfs
jfs

Reputation: 414129

The issue is with time(&future) call that modifies future. difftime() accepts the original future value on my machine:

/** $ make CC="gcc -std=c99" kingsdeb && ./kingsdeb */
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int
main(void) {
  struct tm t = {
    .tm_year=559444 - 1900, .tm_mon=2, .tm_mday=8,
    .tm_hour=13, .tm_min=40, .tm_sec=15, .tm_isdst=-1
  };
  time_t future = mktime(&t);
  if (future == (time_t) -1) {
    fprintf(stderr, "error: mktime returns -1 for %s", asctime(&t));
    exit(EXIT_FAILURE);
  }
  time_t now_time = time(NULL);
  if (now_time == (time_t) -1) {
    perror("time");
    exit(EXIT_FAILURE);
  }
  time_t now_from_future = future;
  if (time(&now_from_future) == (time_t) -1) {
    perror("time(&now_from_future)");
    exit(EXIT_FAILURE);
  }
  double  diff_in_sec = difftime(future, now_time);
  if (diff_in_sec < 1 && future != now_time) {
    fprintf(stderr, "difftime() returned value %f is too small\nfor "
                    "the time difference between (\n%s",
            diff_in_sec, ctime(&future));
    fprintf(stderr, "and\n%s)\n", ctime(&now_time));
    exit(EXIT_FAILURE);
  }
  printf("The current time is %s", ctime(&now_time));
  printf("time(&future)       %s", ctime(&now_from_future));
  printf("The future time  is %s", ctime(&future));
  printf("The diff in sec from now to future is %f\n", diff_in_sec);
  return 0;
}

Output

The current time is Mon Sep  8 13:52:00 2014
time(&future)       Mon Sep  8 13:52:00 2014
The future time  is Fri Mar  8 13:40:15 559444
The diff in sec from now to future is 17590775874495.000000

The output shows that time(&ts) stores the current time into ts. Don't pass future into it.

Upvotes: 1

Petr
Petr

Reputation: 1169

time_t is not big enough to hold 0xFFFFFFFFFFF.

Try this:

printf("%0lli\n%0lli\n", future, 0xFFFFFFFFFFF);

It will return this:

-1
4294971391

Upvotes: 1

Related Questions