How to get a timestamp (date + time) in Matlab

To complete my  Matlab interface for data fitting, I  needed a Timestamp function, namely a function that combine date and time into a single string.

This can be useful when you want to save files having the same base "name" but created at different times.

In Matlab the timestamp is obtained with the command

>>datestr(clock, 0)

which output is

10-nov-2012 14:10:20

Unfortunately this string cannot be used into a filename due to the presence of colons.
In addition I would like to have a string starting with "year-month-day" because it is a much more convenient  way to name files created at different times.
 

My version of TimeStamp that produces a string in the format :

year-month-day-hours-h-minutes-m-second-s

as for example

2012-11-10-14h10m20s

Enjoy!

----------------------------------------------------------------

function [s]=TimeStamp
%[s]=TimeStamp
% time stamp in the format
% year-month-day-hours-h-minutes-m-second-s


% Get current time as date vector

t=clock;

% convert date vector into the string: year-month-day
yyyy_mm_dd=datestr(t, 29);

% convert date vector into the string: day-month-year[blank]hours:minutes:seconds
s=datestr(t, 0);

% get index of the blank
index=find(s==' ');

% remove the string that is before the blank
s=s((index+1):end);

% get the indices of the colons ":"
ii=find(s==':');

%change the first colon into "h" and the second one into "m". Add an "s" at the end of the
%string

h_m_s=strcat(  s(1:(ii(1)-1)), 'h', s( (ii(1)+1): (ii(2)-1)), 'm', s( (ii(2)+1):end), 's');

% concate the two strings
s=strcat(yyyy_mm_dd, '-', h_m_s);

--------------------------------------------------------

alternative link

Comments

Anonymous said…
Great Work

Popular posts from this blog

Where to get research papers for free

Library.nu alternatives

Italian Words in How I Met Your Mother