matlab两种方法将NC文件中的gregorian日期转换成年月日ymd

在读取某一些科研数据集的时候,采用netcdf的存储格式,其中往往会遇到以下的情况:

time             
           Size:       1x1
           Dimensions: time
           Datatype:   double
           Attributes:
                       units         = 'days since 2002-01-01 00:00:00 UTC'
                       long_name     = 'Time'
                       standard_name = 'Time'
                       axis          = 'T'
                       calendar      = 'gregorian'
                       bounds        = 'time_bounds'

其中读取的时间time表示从2002年1月1日至目前所要读取文件时间为止累计的天数。本人目前有两种解决的思路:

方案一 直接采用matlab自带的函数读取

file = ('GRD-3_2022213-2022243_AOD1B_JPL.nc')
ncdisp(file)
time = ncread(file,'time')
dt = datetime((time)*24*3600, 'ConvertFrom', 'epochtime', 'Epoch', '2002-01-01')

得到的结果是


time =

                    7532.5


dt = 

  datetime

   2022-08-16 12:00:00

方案二 利用文件名中包含的年积日转换成年月日

利用下面的函数将年积日转换成年月日

function [year,month,day] = wzq_yd2ymd(year,doy)
%% convert days in year to year-month-day
% modified from: https://blog.csdn.net/qq_41696018/article/details/119647098
    days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31];
    if(mod(year,4)==0 && (mod(year,100)~=0 || mod(year,400)==0))
        days_in_month(2)=29;
    end
    id = doy;
    month = 0;
    day   = 0;
    for i = 1:12
        id = id - days_in_month(i);
        month = i;
        if(id>0)
            continue
        end
        day = id + days_in_month(i);
        break
    end
end 

% 此处以示例数据 GRD-3_2022213-2022243_AOD1B_JPL.nc
[a1,b1,c1] = wzq_yd2ymd(2022,213)
[a2,b2,c2] = wzq_yd2ymd(2022,243)

得到的结果如下:

a1 =

        2022


b1 =

     8


c1 =

     1


a2 =

        2022


b2 =

     8


c2 =

    31

与方案一得到的结果是一致的!

参考资料:

1.https://ww2.mathworks.cn/matlabcentral/answers/617198-convert-epoch-time-to-yyyymmddhhmmss

2.作者:我是水怪的哥 https://www.bilibili.com/read/cv19156925?spm_id_from=333.999.0.0 出处:bilibili

3.https://blog.csdn.net/weixin_45770896/article/details/111311360

你可能感兴趣的:(科研笔记,matlab,开发语言)