How to round milliseconds of datetime Format?

27 次查看(过去 30 天)
Here's an example:
>> dt = datetime("098:17:17:34.475", 'InputFormat', 'DDD:HH:mm:ss.SSS', 'Format', 'DDD:HH:mm:ss.SSS')
dt =
datetime
098:17:17:34.475
>> SecsSinceNewYear = seconds(dt - datetime(dt.Year, 1, 0, 0, 0, 0, 0))
SecsSinceNewYear =
8529454.475
>> dt = datetime(0, 1, 0, 0, 0, SecsSinceNewYear, 'Format', 'DDD:HH:mm:ss.SSS')
dt =
datetime
098:17:17:34.474
>> string(dt)
ans =
"098:17:17:34.474"
>> dt.Format = 'DDD:HH:mm:ss.SSSSSSSSS'
dt =
datetime
098:17:17:34.474999999
Notice that the input ends in 475 milliseconds, but when displayed there seems to be a precision error that ends up not rounding and displays 474 milliseconds. So when I attempt to convert the datetime back into it's original string form the millisecnds have changed from 475 to 474.
Is there anyway to avoid this error introduced by converting these formats?

采纳的回答

Brett Mather
Brett Mather 2020-6-29
Following up after getting support from MathWorks:
This was identified as a bug that exists in at least R2017b (maybe others) but is supposedly fixed in 2018a and later (I haven't checked as I'm using 2017b).
To further clarify the bug:
>> dt = datetime(0, 1, 0, 0, 0, 8.529454475000000e+06, 'Format', 'DDD:HH:mm:ss.SSS')
dt =
datetime
098:17:17:34.474
Notice that the double I input for 'seconds' in datetime ends in 475 milliseconds and the output from datetime formatted to show milliseconds shows 474.
To work around this in 2017b do the following to split the original double into 'seconds' and 'milliseconds' before input to datetime:
>> start = 8.529454475000000e+06;
>> s = floor(start);
>> ms = round((start - s)*1000);
>> dt = datetime(0, 1, 0, 0, 0, s, ms, 'Format', 'DDD:HH:mm:ss.SSS')
dt =
datetime
098:17:17:34.475

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Dates and Time 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by