简体   繁体   中英

how to find time difference between two times in MATLAB in custom format?

In MATLAB software, I want to calculate algorithm working time in custom format. It works, but how to customize it to show this format: year:month:day hour:minutes:seconds:miliseconds

It shows: '01 00, 0000 00:00:06 051', The result is not correct because of 01 on the first(month).

startTime=datetime('now');
%some working.....
endTime=datetime('now');
workedTime= datestr((endTime-startTime), 'mm dd, yyyy  HH:MM:SS FFF');

There is no builtin MATLAB function because duration in months is problematic (a month can be 28, 29, 30 or 31 days long).

You can usebetween function that returns calendar math differences.

Manual formatting is required, because calendar functions don't support your desired format.
First use split function to split the calendar duration to years, months, days, time, then use sprintf for manual formatting:

[y,m,d,t] = split(between(startTime, endTime), {'years','months','days','time'});
workedTime = sprintf('%02d %02d, %04d  %s', m, d, y, datestr(t, 'HH:MM:SS FFF'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM