get GPS time to calulate time since referencje epoch
100 views (last 30 days)
Peter Perkins on 24 Nov 2020
Marta, that depends on what you mean by "GPS time".
MATLAB doesn't yet have direct support for GPS time, but if all you want is elapsed time since the GPS origin, it's pretty simple, although not obvious:
>> t = datetime('now','TimeZone','UTC')
>> GPS0 = datetime(1980,1,6,0,0,0,'TimeZone','UTCLeapSeconds')
>> tLS = t; tLS.TimeZone = 'UTCLeapSeconds'
>> deltaT = tLS - GPS0; deltaT.Format = 's'
Why this works is a bit confusing, but bear with me. The GPS timeline doesn't observe leap seconds, so it drifts from the real-world UTC timeline as the years go by (currently 18s apart). But 6-Jan-1980 is where the two time lines are sync'ed up, and elapsed time is the same on both timelines. So you can subtract 6-Jan-1980 from the current time and get the correct elapsed time in either time line.
The trick is that in MATLAB, you have to do this using datetime's 'UTCLeapSeconds' "time zone". Why is that? Hardly anyone wants leap seconds to randomly creep into their date/time calculations, so MATLAB leaves them out by default (that's exactly how POSIX time works, and NTP too). That's true of calculations using unzoned datetimes, as well as datetimes with time zones, including 'UTC'. If you care about leap seconds, you opt in by using 'UTCLeapSeconds'. And to get the right elapsed time in this calculation, you have to account for leap seconds, not just ignore them.
It sounds like that elapsed time is what you are looking for. GPS time is often expressed in various ways (e.g. http://leapsecond.com/java/gpsclock.htm). It's straight-forward to get to the week/second representation:
>> weeks = floor(seconds(deltaT)/(7*86400))
>> secs = rem(deltaT,seconds(7*86400))
If you want a human-readable timestamp, it's also easy, but also not obvious. Just add your elapsed time to 6-Jan-1980 unzoned.
>> datetime(1980,1,6) + deltaT
18s ahead, because GPS counted the 18 leap seconds since 1980 as regular non-leap seconds. But remember, to calculate elapsed time, you need to do it using 'UTCLeapSeconds'.