1

I am writing a code in c and I need to add milliseconds to the current time given by :

current_time = time(NULL);
loc_time=localtime(&current_time);

Say the local time is 20:00:00:10. I want to adding 10 seconds and display it so it displays 20:00:00:20. I am fairly new to c so any help is much appreciated. I am confused as time is in int format and, to add milli seconds I will have to add .001 seconds to the current second which is not an int.

James Mark
  • 141
  • 2
  • 3
  • 6

3 Answers3

5

time_t is just an integer in seconds, so you simply add 10 to it:

time_wanted = time(NULL) + 10;
loc_time=localtime(&time_wanted);
Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
  • 1
    In most cases you're right but it's implementation defined. It's a floating or an integer type. But also that sais nothing about the internal bit representation of the `time_t` type, see: https://stackoverflow.com/a/25198359/8051589 and here: https://stackoverflow.com/a/13855956/8051589. – Andre Kampling Aug 10 '17 at 13:34
  • @AndreKampling: While the spec allows it to be a floating point type, I'm not aware of any system where it is. But it actually doesn't matter -- either way you can do arithmetic on it. – Chris Dodd Aug 10 '17 at 17:50
0

Since time() "returns the time as the number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC).", all you need to do is just add 10 to its return value:

time_t timeNow;
struct tm* time_info;
time(&timeNow);
time_info = localtime(&timeNow);
char timeStr[sizeof"HH:MM:SS"];
strftime(timeStr, sizeof(timeStr), "%H:%M:%S", time_info);
printf("Time now: %s\n", timeStr);

// add 10 seconds:
timeNow += 10;
time_info = localtime(&timeNow);
strftime(timeStr, sizeof(timeStr), "%H:%M:%S", time_info);
printf("New time: %s\n", timeStr);

See full example

LihO
  • 41,190
  • 11
  • 99
  • 167
-1

time returns the time in seconds, so you could simply add as in

time_t soon = current_time + 10;
s.bandara
  • 5,636
  • 1
  • 21
  • 36