2

I have an array of Epoch times that include fractional (nanoseconds). I have reviewed Converting Epoch to Date in Matlab but still cannot seem to convert to the correct date. I must be missing something simple.

Example data: 1548348497.191261

I am using the code in the link above.

time_unix_nanos = 1548348497.191261;
millis = round(time_unix_nanos);
nanos = time_unix_nanos - 1e6 * millis;
time_matlab = round(864e5 * (millis - datenum('1970', 'yyyy')));
s = [datestr(time_matlab, 'yyyy-mm-dd hh:mm:ss.FFF;), num2str(nanos)];

fprintf('s: = %f\n',s);

Two desired outputs Full date format: yyyy-mm-dd HH:mm:ss.SSS Just time format: HH:mm:ss.SSS

Thanks in advance!

D Chase
  • 85
  • 7

1 Answers1

1

It seems you've mistaken the conversion of unixtime to matlab time with matlab time to unixtime.

time_unix_nanos = 1548348497.191261;
millis = round(time_unix_nanos / 1e6);  % You had also a /1e6 missing here
nanos = time_unix_nanos - 1e6 * millis;
% The following line converts unix time to matlab time. The line you used was doing the opposite
time_matlab = datenum('1970', 'yyyy') + millis / 864e5;

% First desired date format
s1 = [datestr(time_matlab, 'yyyymmdd HH:MM:SS.FFF;'), num2str(nanos)]
% Second desired date format
s2 = [datestr(time_matlab, 'HH:MM:SS.FFF;'), num2str(nanos)]

gives

>> s1
    '19700101 00:00:01.548;348497.1913'


>> s2
    '00:00:01.548;348497.1913'
gehbiszumeis
  • 3,525
  • 4
  • 24
  • 41