gpt4 book ai didi

c# - 将 Matlab Datenum 转换为 Datetime

转载 作者:太空狗 更新时间:2023-10-29 23:03:01 27 4
gpt4 key购买 nike

-我希望转换 Matlab 串行时间(datenum,如 t_matlab=now)
到 c# 日期时间(如 var t_cs = DateTime.Now.Ticks)。

知道怎么做吗?

[编辑]我找到了一种方法,但仍然不确定这是否是最好的方法。
[Edit2] 修复了错误的 DateTimes,感谢 Jonas!

function cstime = datenum2datetime( matlabSerialTime )
%Convert matlab serial time (datenum) to .net datenum.
%
% Example:
% ntTime = datenum2datetime(now)
% cstime = datenum2datetime([734539.4717013890 734539.5051388888]);
%
% See also datenum.

% using System.DateTime.Parse(string).Ticks to convert to DateTime format.
% t1 = now; t2 = now+1; matlab_times = [t1 t2];
% cs_times = [System.DateTime.Parse(datestr(t1)).Ticks ...
% System.DateTime.Parse(datestr(t2)).Ticks]
% aver = diff(cs_times)/diff(matlab_times);
% offver = cs_times(1) - matlab_times(1)*aver;

a = 10^7*60*60*24;
offset = -367*10^7*60*60*24;
cstime = a*matlabSerialTime + offset;

最佳答案

编辑:对 jarr 的回答感到惊讶,我进一步调查了。事实证明,问题中 sharhar_m 给出的示例时间点是错误的(很抱歉没有早点检查)。

综上所述,题中给出的函数有367-281=86天错误,应该更正为

function cstime = datenum2datetime( matlabSerialTime )
cstime = 10^7*60*60*24*(matlabSerialTime - 367);

现在详细说说,以防有人感兴趣:你声称

% {05-Feb-2011 11:19:15} in System.DateTime is 634399319550000000

但是在 MATLAB R2010b 中

sdt =System.DateTime(634399319550000000); 
[sdt.Day sdt.Month]

返回 [2 5],因此您的 DateTime 值实际上是 5 月 2 日,而不是 2 月 5 日!!计算出正确的值集

cs_times = [System.DateTime.Parse('05-Feb-2011 11:19:15').Ticks ...
System.DateTime.Parse('05-Feb-2011 12:07:24').Ticks]

给出 [634325015550000000 634325044440000000]

时间单位缩放

您的因子 a 是 10^7*60*60*24 即 MATLAB 以“天”为单位存储日期/时间(时间为小数天),C# 将时间存储为“滴答” ,即“10^-7 秒”的数量。您可以通过为 a 输入精确值来避免一些舍入错误。

引用时间点的差异

以天数表示的偏移量b (b/a) 告诉您它们的“时间原点”相隔 367 天;使用 b 的旧值,结果为 281 天。 datestr 状态的 MATLAB 文档

"A serial date number represents the whole and fractional number of days from 1-Jan-0000 to a specific date. The year 0000 is merely a reference point and is not intended to be interpreted as a real year in time."

(即使运行 datestr(0,'dd-mm-yyyy HH-MM-SS') 显示引用点实际上是 0-Jan-0000)。 C# ticks

"number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001, which represents DateTime.MinValue. It does not include the number of ticks that are attributable to leap seconds."

因此,总而言之,两个系统之间的“时间起源”相差一个闰年和一天,因此相差 367 天。如果你真的想处理很久以前的真实日期,你将不得不使用 Gregorian calendar改革和奥古斯都对闰年错误应用的更正Julian calendar考虑到 8 年级之前...但我怀疑这在这里​​是否有意义 ;-)。

关于c# - 将 Matlab Datenum 转换为 Datetime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5855208/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com