Add up millisecond steps to a certain datetime

98 ビュー (過去 30 日間)
Karl Drenker
Karl Drenker 2021 年 12 月 15 日
編集済み: Siddharth Bhutiya 2021 年 12 月 30 日
I try to add milliseconds to a certain datetime. In dtStart.Var1 the times are in milliseconds (25,50,75, ...). I would like to add this to my current time_of_day. With my code, however, in the end I lose the milliseconds when converting back to datetime.
DateVector = datevec(time_of_day);
A = (dtStart.Var1/1000)+DateVector(:,6);
C = cat(2,DateVector,A);
B = C(:,[1,2,3,4,5,7]);
time = datetime(B,'InputFormat','yyyy-MM-dd HH:mm:ss.SSS');

採用された回答

Chunru
Chunru 2021 年 12 月 15 日
Use "Format" for output (not "InputFormat" which is for input).
DateVector = [2021 12 15 01 30 05]
DateVector = 1×6
2021 12 15 1 30 5
A = DateVector;
A(6) = (345/1000)+A(:,6) % ms: 345
A = 1×6
1.0e+03 * 2.0210 0.0120 0.0150 0.0010 0.0300 0.0053
time = datetime(A, 'Format','yyyy-MM-dd HH:mm:ss.SSS')
time = datetime
2021-12-15 01:30:05.345
  1 件のコメント
Karl Drenker
Karl Drenker 2021 年 12 月 15 日
Perfect thank you for your quick answer !!

サインインしてコメントする。

その他の回答 (1 件)

Siddharth Bhutiya
Siddharth Bhutiya 2021 年 12 月 30 日
編集済み: Siddharth Bhutiya 2021 年 12 月 30 日
You don't need to convert the datetime into a datevec. You can convert your millisecond values into a duration using the milliseconds function and directly add it to the datetime.
>> dt = datetime(2021,12,(1:5)',"Format","dd-MMM-uuuu HH:mm:ss.SSS")
dt =
5×1 datetime array
01-Dec-2021 00:00:00.000
02-Dec-2021 00:00:00.000
03-Dec-2021 00:00:00.000
04-Dec-2021 00:00:00.000
05-Dec-2021 00:00:00.000
>> millisVals = [100;200;300;123;456];
>> dt = dt + milliseconds(millisVals)
dt =
5×1 datetime array
01-Dec-2021 00:00:00.100
02-Dec-2021 00:00:00.200
03-Dec-2021 00:00:00.300
04-Dec-2021 00:00:00.123
05-Dec-2021 00:00:00.456

カテゴリ

Help Center および File ExchangeDates and Time についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by