2

I have a date like: 171115 183130 (17-11-15 18:31:30). I using an API that required me to supply the date based on the week number but since it's for a GPS service it needs to be the week number counting from 1980 (first epoch)

I couldn't find any library in C that takes into consideration leap days/seconds. Any ideas?

For example, week 1873 should be 2015 11 30.

Toby Speight
  • 25,191
  • 47
  • 61
  • 93
matt
  • 2,252
  • 5
  • 29
  • 54
  • Those of us who muddle and muck with time, do not think this is off-topic. The GPS Epoch should not be marginalized in these lands, just because the majority uses the Unix Epoch. Please keep GPS Epoch related questions open. – Xofo Apr 09 '19 at 16:16
  • See also [Ticks between Unix epoch and GPS epoch](https://stackoverflow.com/q/20521750/2410359) and [What is a GPS epoch?](https://gis.stackexchange.com/questions/281223/what-is-a-gps-epoch) – chux - Reinstate Monica Apr 09 '19 at 20:03

2 Answers2

3

Since the date shows the day and time separately, you do not need to worry about leap seconds.

Use the C library API to convert from DDMMYY to the number of seconds since the C epoch (1/1/1970), subtract the number of seconds until 1/1/1980 and divide the result by 7*24*3600 to get the number of weeks elapsed from 1/1/1980.

chqrlie
  • 114,102
  • 10
  • 108
  • 170
3

By using difftime() no need to assume Jan 1, 1970 epoch. difftime() returns the difference in the 2 time stamps as a number of seconds (double). The return value is independent of the number type and epoch used for time_t.

Use mktime() to convert YMD to time_t.
Open question: timezone not mentioned in OP's post

#include <stdio.h>
#include <time.h>

time_t TimeFromYMD(int year, int month, int day) {
  struct tm tm = {0};
  tm.tm_year = year - 1900;
  tm.tm_mon = month - 1;
  tm.tm_mday = day;
  return mktime(&tm);
}

#define SECS_PER_WEEK (60L*60*24*7)

int GPSweek(int year, int month, int day) {
  double diff = difftime(TimeFromYMD(year, month, day), TimeFromYMD(1980, 1, 1));
  return (int) (diff / SECS_PER_WEEK);
}

int main(void) {
  printf("%d\n", GPSweek(2015, 11, 30));
  return 0;
}

Output

1873
chux - Reinstate Monica
  • 127,356
  • 13
  • 118
  • 231
  • NOTE - The GPS epoch is 0000 UT (midnight) on January 6, 1980. GPS time is not adjusted and therefore is offset from UTC by an integer number of seconds, – Xofo Apr 09 '19 at 16:27