Matlab 日期与DOY之间的转换

datetime()
day()

完整代码

%%This code is used to convert between DOY and DATE. 
clc;
clear;
%% DATE TO DOY
%%% If there is only one date to calculate, run this part.
Y = 2020; 
M = 9;
D = 1;
t = datetime(Y, M, D);%Store temporary date variables
DOY = day(t,dayofyear);
sp_time = [num2str(Y),num2str(DOY,%03d)];%Connect year and DOY
disp([DOY=,sp_time])
%%% If there are many dates to calculate, store them in Excel and run this part.
filePath = D:datadateToDOY.xlsx;
data = xlsread(filePath);
count = size(data,1);
result = zeros(count,1); %Creat an empty matrix
for i = 1:count
    Y = data(i,1);
    M = data(i,2);
    D = data(i,3);
    tempDate = datetime(Y, M, D);%Store temporary date variables
    DOY = day(tempDate,dayofyear);
    sp_time = strcat(num2str(Y),num2str(DOY,%03d));%Connect year and DOY
    result(i,1) = str2double(sp_time);
end
xlswrite(filePath,result,Sheet1,D1);
%% DOY To DATE
data = xlsread(filePath,Sheet1,D:D);
result = {
          
   };
for j = 1:length(data)
    DOY = num2str(data(j));
    Y = str2num(DOY(1:4));
    doy = str2num(DOY(5:7));
    date = datetime(Y,1,doy);
    result{
          
   j,1} = date;
end
writecell(result,filePath,Sheet,1,Range,E1);

#结果 (用得比较多,整理笔记以备复习)

经验分享 程序员 微信小程序 职场和发展