MATLAB: Timestamp function or class object

timestamp

Hey Guys, I want to send and record the Timestamp when i create a Message. How to send timestamp along with Message via fprintf or fwrite or any other command Can someone write a function or create a class or help me proceed with this.

Best Answer

You cannot get microseconds when you use datestr and now. The underlying representation is only accurate to less than 10 microseconds for times near this century. If you want to print the guaranteed inaccurate microseconds then you will need to format them yourself.
TheTime = now;
dv = datevec(TheTime);
dv(6) = 0;
reconstructed_time = datenum(dv);
timediff = TheTime - reconstructed_time;
diff_secs = timediff * 24*60*60;
s = sprintf( '%s%09.6f', datestr(dv, 'yyyy-mm-dd HH:MM:'), diff_secs)
The reason for not just grabbing dv(6) and printing it is that in my testing I can see that MATLAB rounds it to the 1000'th of a second.
It is, of course, bad practice to try to create microsecond time stamps of a time that is inherently less than 10 microsecond accuracy. Therefore you should not be using datenum as your time representation. Because if you were using datetime objects like we suggested several days ago, then you would have nanosecond resolution and you would be able to format your objects with up to 9 decimal places of fraction in the time format; see http://www.mathworks.com/help/matlab/ref/datetime-properties.html#prop_Format
Just take your datetime object, assign an appropriate Format property to it, and then char() will format the time appropriately as a string.