get month of date from string

조회 수: 3 (최근 30일)
Nooshin Mahmoodi
Nooshin Mahmoodi 2018년 10월 25일
댓글: Guillaume 2018년 10월 25일
I used this code, for exporting the month of years, but it doesn't work for all of my dates, and return NAN for some dates... what is the problem?
if true
mnth= month(datetime(date,'InputFormat','yyyy/MM/dd')) end
  댓글 수: 2
KSSV
KSSV 2018년 10월 25일
YOur date variable at the end is 0..so it is NaN.
Nooshin Mahmoodi
Nooshin Mahmoodi 2018년 10월 25일
this nan is not just for the last one I have a lot of them.

댓글을 달려면 로그인하십시오.

채택된 답변

Guillaume
Guillaume 2018년 10월 25일
편집: Guillaume 2018년 10월 25일
what is the problem?
Your cell array date contains some dates that are not valid and are thus converted to NaT (Not a Time) by datetime. For example, date{2307} is the 30th of February 1389 which matlab rightfully says is not a valid date. In total you have 501 such invalid dates.
In addition, the last element of your cell array is empty.
Note: you can always remove these invalid dates from your array:
d = datetime(date, 'InputFormat','yyyy/MM/dd');
d(isnat(d)) = []; %remove invalid dates
mnth = month(d)
  댓글 수: 2
Nooshin Mahmoodi
Nooshin Mahmoodi 2018년 10월 25일
but I need this date, my date is in Persian ...I dont want to delete them there is not any way introduce this to Matlab, for 6 first month I have 31 days, and 6 second WE have 30 days. I have this problem with years too.for example here I have two years 1389 and 1390 but, it brings nan again.
Guillaume
Guillaume 2018년 10월 25일
Unfortunately, datetime and all its functions (including month) assume a gregorian calendar. They're not designed to work with the islamic calendar. I am afraid that you cannot use datetime with islamic dates.
For your purpose of extracting months from islamic dates in the form 'yyyy/MM/dd' the simplest would be to use a regular expression:
mnth = str2double(regexp(date, '(?<=\d+/)\d+', 'match', 'once'))
The regular expresion:
  • (?<=...) look behind for a pattern. Stuff to match before what you want to extract. That stuff being:
  • \d+/: 1 or more numeric digit (the \d+), followed by a litteral /. Basically, look behind for the year.
  • \d+: match one or more numeric digit. Matches the month.
Note that if you wanted to extract the day, the pattern would be:
dy = str2double(regexp(date, '(?<=\d+/\d+/)\d+', 'match', 'once'))

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Calendar에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by