How can I programmatically change all my matlab code to use "datetime" rather than "datestr(now)" ?
Show older comments
Matlab R2022b does not recommend using "datestr". I would like to quickly and easily replace that command in all my matlab programs to "datetime". Can I do this programatically?
4 Comments
Walter Roberson
on 29 Sep 2022
If it is a single file, then use find and replace datestr(now) to datetime('now')
Untested (and be SURE to have backups first), something like
d=dir('*.m');
for i=1:numel(d)
f=readlines(d(i).name);
f=strrep(f,"datestr(now)","char(datetime('now'))"); % include translation to char string
writematrix(f,d(i).name,'QuoteStrings',0 ) % use writelines w/ R2022a and after
end
should do the trick...
Walter Roberson
on 30 Sep 2022
You would writelines() instead of writematrix()
writelines wasn't introduced yet in R2020b, Walter...not until R2022a
Will also probably have to use the 'QuoteStrings',0 named parameter to avoid putting quotes around every line in an m-file...and as @per isakson notes, while it may make the substitution, that alone doesn't mean the change is transparent elsewhere. There is only one syntax form in question here, though, but that it will be a datetime instead of character string means it'll probably error when used elsewhere.
One would presume there aren't many of these in much code, however, so it may be just wait and find the then, but I'd also follow his recommendation to only make the switch in new code (or other code that is being actively worked on otherwise, maybe, as well).
grep will let one find instances/locations to go look at though, so one could also build a filter first of m-files containing the idiom.
Accepted Answer
More Answers (1)
You can use control-shift-f and search for datestr(now).
Unfortunately that multi-file search capability does not (yet) have a replace capability. So for each line of code found, double click on it in the list of hits to bring up that file in the editor.
Now type control H and tell it to replace datestr(now) with char(datetime).
They're the same. Viz:
datestr(now)
char(datetime)
1 Comment
Image Analyst
on 30 Sep 2022
Unless you have hundreds of files, this way will be faster than writing and debugging a program to do it.
Categories
Find more on Time Series Objects in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!