How to intelligently convert the number of seconds to a date value using C

In my embedded Linux application, I have a counter counter that increments 1 every 10 nanoseconds since January 1, 00:00:00 2014.

I want to be able to select the current value of the counter counter, print it as the current date-date (year, month, day, hour, minute, second and millisecond) of my system, which already considers such as a leap year, February, which has 28/29 days etc., and this is the use of pure C methods (from time.h, etc.).

But I don’t know how to do it ... At the moment I have an equivalent value in seconds, so I know how many seconds have passed since the start of the transfer, but not how to go from this to the current date-time value with everything corrected, only in Qt, which is not available (and in this case, the Internet did not help much, how could I understand the explanations on cplusplus.com, etc.)

Any help was appreciated.

+4
source share
2 answers

Use gmtime().

Just divide the number of marks to get integer numbers of seconds, and add an offset to change the era from January 1, 2014 to January 1, 1970.

void print_time(unsigned long long tick_count) {

  static const unsigned long ticks_per_sec = 100000000L;
  static const time_t epoch_delta = 16071L*24*60*60;
  time_t seconds = tick_count/ticks_per_sec + epoch_delta;

  unsigned long fraction = tick_count%ticks_per_sec;
  struct tm tm = *gmtime(&seconds);
  printf("%4d-%02d-%02d %02d:%02d:%02d.%03lu\n",
      tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
      tm.tm_hour, tm.tm_min, tm.tm_sec,
      fraction/10000);
}

[After Accept Edit]

OP: " time.h, , 1970 , "

- mktime(). , @DavidEisenstat. tm_sec, int (, 32 ), 2014-282. mktime() . tm_sec 16-, tm_mday, tm_hour, tm_min, tm_sec.

void print_time2(unsigned long long tick_count) {

  static const unsigned long ticks_per_sec = 100000000L;
  unsigned long fraction = tick_count%ticks_per_sec;
  unsigned long long secondsFromJan12014 = tick_count/ticks_per_sec;
  struct tm tm = {0};
  tm.tm_year = 2014 - 1900;
  tm.tm_mday = 1;
  tm.tm_sec = secondsFromJan12014;

  if (mktime(&tm) == (time_t)(-1)) Handle_Failure();
  printf("%4d-%02d-%02d %02d:%02d:%02d.%03lu\n",
      tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
      tm.tm_hour, tm.tm_min, tm.tm_sec,
      fraction/10000);
}
+3

-, . -, 1970-01-01, , UTC 2014-01-01 00:00:00. date Linux :

date -u -d "2014-01-01 00:00" +%s 1388534400

, - :

time_t current = 1388534400 + my_10_nano_time_function()/100000000;

time_t, , localtime, gmtime strftime.

, time_t , , - :

(my_10_nano_time_function()%/100000000)/100000

+2

All Articles