【问题标题】:How to convert datetimes to days of the year?如何将日期时间转换为一年中的天数?
【发布时间】:2019-11-30 22:03:43
【问题描述】:

假设DTdatetime 类型的向量。我怎样才能知道他们一年中的日子?

这是一个近似值,但我找不到正确的函数:

month(DT) * 30 + day(DT)

【问题讨论】:

    标签: matlab datetime data-conversion


    【解决方案1】:

    您可以将 Matlab 的 day 函数与日期时间元素的向量一起使用(参见 doc

    t = [datetime('yesterday');datetime('today');datetime('tomorrow')]; % vector of datetime
    
    day( t, 'dayofyear')
    

    这将给出年份数字,从 1 到 365 或 366,具体取决于年份。

    ans =

    334 335 336

    【讨论】:

      【解决方案2】:

      你可以使用datetimebetween如下:

      d = datetime; %Read current time (just for the example).  
      jan_1st = datetime(d.Year, 1, 1); %Create datetime object of January fist in year of d.  
      day_in_year = between(jan_1st, d, 'Days'); %Get day in year.  
      

      结果是一个calendarDuration 对象:334d

      要转换为标量,请使用split

      day_in_year = split(day_in_year, 'Days') + 1; % Add one in case the first day of the year is day 1 and not 0
      

      由于datetime(d.Year, 1, 1) 的使用,将解决方案应用于datetime 的向量可能需要for 循环。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-06
        • 1970-01-01
        • 2014-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-07
        • 2011-12-18
        相关资源
        最近更新 更多