I have some data files with Unix timestamps (in this case, number of milliseconds since Jan 1, 1970 00:00 UTC). I would like to convert these to human-friendly date/time str
How about
date = datestr(unix_time/86400 + datenum(1970,1,1))
if unix_time
is given in seconds, unix_time/86400
will give the number of days since Jan. 1st 1970. Add to that the offset used by Matlab's datenum
(datenum(0000,1,1) == 1
), and you have the amount of days since Jan. 1st, 0000. This can be easily converted to human-readable form by Matlab's datestr
.
If you have milliseconds, just use
date = datestr(unix_time/86400/1000 + datenum(1970,1,1))
Wrapped in functions, these would be
function dn = unixtime_to_datenum( unix_time )
dn = unix_time/86400 + 719529; %# == datenum(1970,1,1)
end
function dn = unixtime_in_ms_to_datenum( unix_time_ms )
dn = unix_time_ms/86400000 + 719529; %# == datenum(1970,1,1)
end
datestr( unixtime_to_datenum( unix_time ) )
Newer versions of MATLAB (verified in R2015a) have a datetime type that is useful for working with and formatting dates and times. You can convert UNIX timestamps into a MATLAB datetime with
dt = datetime( unix_time, 'ConvertFrom', 'posixtime' );
and then use datestr as before for formatting as a string
datestr( dt )