How do I round this datetime to the nearest 0.1 second?

81 views (last 30 days)
I have the following datetime: 01-Oct-2020 04:49:10.350
How would I use MATLAB to round the millisecond value to the nearest tenth? i.e. I want the datetime to be rounded to: 01-Oct-2020 04:49:10.4
I know there is the dateshift function in MATLAB but the lowest you can go is rounding to seconds. Is there a way to go even further?

Accepted Answer

Adam Danz
Adam Danz on 18 Nov 2021
dt = datetime(' 01-Oct-2020 04:49:10.350','Format', 'dd-MMM-uuuu HH:mm:ss.SSS')
dt = datetime
01-Oct-2020 04:49:10.350
dtRound = dateshift(dt,'start','minute') + seconds(round(second(dt),1))
dtRound = datetime
01-Oct-2020 04:49:10.400

More Answers (1)

the cyclist
the cyclist on 18 Nov 2021
Edited: the cyclist on 18 Nov 2021
This is awkward, but it works. Guessing there is a better way.
% Define original datetime input
dt = datetime('01-Oct-2020 04:49:10.350');
% Define new datetime, by calculating difference from rounded seconds, and
% incrementing
new_dt = dt + duration([0 0 round(second(dt),1) - second(dt)]);
% Show that the new datetime is incremented
seconds(new_dt - dt)
ans = 0.0500

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!