get GPS time to calulate time since referencje epoch

81 views (last 30 days)
Does anyone know is there any function that will give me GPS time (now)? I need it to calculate time since reference epoch (tk = t - to) in seconds.

Accepted Answer

Peter Perkins
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')
t =
datetime
24-Nov-2020 16:25:14
>> GPS0 = datetime(1980,1,6,0,0,0,'TimeZone','UTCLeapSeconds')
GPS0 =
datetime
1980-01-06T00:00:00.000Z
>> tLS = t; tLS.TimeZone = 'UTCLeapSeconds'
tLS =
datetime
2020-11-24T16:25:14.119Z
>> deltaT = tLS - GPS0; deltaT.Format = 's'
deltaT =
duration
1290270332.11899 sec
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))
weeks =
2133
>> secs = rem(deltaT,seconds(7*86400))
secs =
duration
231932.118987061 sec
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
ans =
datetime
24-Nov-2020 16:25:32
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'.

More Answers (0)

Categories

Find more on Dates and Time in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!