matlabdatetimecells

How can I convert one date and time from two colums?


Im trying to convert the first two columns of a cell into a Matlab time. First column {1,1} is the date in YYYY-MM-DD format and the second is the time in HH:MM format.

Any ideas where I'm going wrong? My code:

    file = 'D:\Beach Erosion and Recovery\Bournemouth\Bournemouth Tidal 
    Data\tidal_data_jtide.txt'
    fileID = fopen(file);
    LT_celldata = textscan(fileID,'%D%D%D%D%d%[^\n\r]','delimiter',',');
    formattime = 'yyyy-mm-dd HH:MM'
    date = LT_celldata{1,1};
    time = LT_celldata{1,2};
    date_time = datenum('date','time'); code

Screenshot below is LT_celldata{1,1} :

enter image description here


Solution

  • You can combine variables date and time with the following code:

    date = datetime(LT_celldata{1,1},'InputFormat','yyyy-MM-dd');
    time = datetime(LT_celldata{1,2},'InputFormat','HH:mm:ss','Format','HH:mm:ss');
    
    myDatetime = datetime(date + timeofday(time),'Format','yyyy-MM-dd HH:mm:ss');
    

    The code uses timeofday function to combine date and time information from the two different variables. You may find more information and examples at this documentation page.