how to convert dates in matlab

1 view (last 30 days)
Biki
Biki on 7 Apr 2021
Edited: dpb on 8 Apr 2021
I have a series of dates such as
Date=[1/1/50
1/2/50
1/3/50
1/4/50
1/5/50
1/6/50
1/7/50
1/8/50
1/9/50
1/10/50
1/11/50
1/12/50]
being in the format of dd/mm/yy (from 1950 going to 2019)
how do i convert these numbers to dates because right now matlab calculates them as they are divisions.
  2 Comments
dpb
dpb on 7 Apr 2021
Need to either
  1. Read them in as text strings that can include the punctuation, or
  2. Read them as numbers, but as separate vectors of year, month, day
Then use datetime to convert to the MATLAB class.
In what form do you have the data from which to start would be what we would need to know to give more precise code.
NB: You'll have some potential issues in use 2-digit years over the turn of the century; if you can clean up the input source to have four-digit years, you'll be well served. It can be made to work, but would be much cleaner the other way.
Biki
Biki on 7 Apr 2021
I've made it so the data is in dd/mm/yyyy and they are just copy pasted from excel onto matlab like shown in the question. What code would make it so that matlab recognizes this as a date? Thanks

Sign in to comment.

Answers (1)

Star Strider
Star Strider on 7 Apr 2021
I have no idea what file format they currently exist in, or how you are reading them.
Creating ‘datefile.txt’ from the posted vector in MS Notepad (attached), then reading them:
fidi = fopen('datefile.txt','rt');
D = textscan(fidi, '%s');
fclose(fidi)
DN = datenum([D{:}], 'dd/mm/yy')
DV = datevec(DN)
DT = datetime(D{:}, 'InputFormat','dd/MM/yy')
provides:
DV =
2050 1 1 0 0 0
2050 2 1 0 0 0
2050 3 1 0 0 0
2050 4 1 0 0 0
2050 5 1 0 0 0
2050 6 1 0 0 0
2050 7 1 0 0 0
2050 8 1 0 0 0
2050 9 1 0 0 0
2050 10 1 0 0 0
2050 11 1 0 0 0
2050 12 1 0 0 0
DT =
12×1 datetime array
01-Jan-2050
01-Feb-2050
01-Mar-2050
01-Apr-2050
01-May-2050
01-Jun-2050
01-Jul-2050
01-Aug-2050
01-Sep-2050
01-Oct-2050
01-Nov-2050
01-Dec-2050
so you will likely need to adjust them to the corect year.
  11 Comments
Biki
Biki on 8 Apr 2021
thank you for both answers!

Sign in to comment.

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!