Why does my datestr return weird result?

I am experiencing some problem returning the correct results for my datestr function. When I execute the following script inside the command window:
datestr('18/10/2011 5:05:55 PM','dd/mm/yyyy HH:MM:SS PM')
the output came out as: 02/04/0024 5:05:55 PM
When I execute the following:
datestr('10/18/2011 5:05:55 PM','dd/mm/yyyy HH:MM:SS PM')
the output came out as: 18/10/2011 5:05:55 PM
Is is something to do with my Matlab setting? Basically I want to convert the given string (a time format written as string in dd/mm/yyyy HH:MM:SS pm) into Matlab datestr in dd/mm/yyyy HH:MM:SS pm format
Thanks in advance, Nu'man.

 채택된 답변

the cyclist
the cyclist 2011년 12월 15일

0 개 추천

When doing string-to-string date conversion, MATLAB assumes that the first input is in "MATLAB standard dateform", which will be mm/dd/yyyy etc. If you want to use a different dateform, you must first convert that to MATLAB standard dateform (using datenum), then convert it back using datestr.
Your second example is in standard dateform, and is correctly converted; your first is not (because it is in dd/mm/yyyy).
This is stated in the "Tips" section of "doc datestr", and in the last paragraph of "help datestr".

댓글 수: 1

Numan
Numan 2011년 12월 15일
Cool, thanks. I didnt notice 'help datestr' is different from 'doc datestr'. 'help datestr' did explain the tip section better.

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

추가 답변 (2개)

Jan
Jan 2011년 12월 15일

0 개 추천

Sorry, I do not get the point. You have a string in the format:
dd/mm/yyyy HH:MM:SS pm
and want to get a string in the format:
dd/mm/yyyy HH:MM:SS pm
???
Numan
Numan 2011년 12월 15일

0 개 추천

The reason behind this question is because I want to run a sql based on the user date input, the input string can be: '*', '*-30d', '18/10/2011' or '18/10/2011 5:05:55 PM'
Based on these inputs I want to manipulate it so the string appear as 'dd/mm/yyyy HH:MM:SS pm' format. Currently I've got the following in place to handle the input but keep getting the odd result.
symbol_star=regexpi(from, '[*-]', 'match');
[~,symbol_starc]=size(symbol_star);
switch symbol_starc
case 1
mod_from=datestr(now,'dd/mm/yyyy HH:MM:SS PM');
otherwise
symbol_minus=regexpi(from, '[-]', 'match');
[~,symbol_minusc]=size(symbol_minus);
switch symbol_minusc
case 1
dayminus=regexpi(from, '\d*', 'match');
dayminus=str2double(cell2mat(dayminus));
mod_from=datestr(now-dayminus,'dd/mm/yyyy HH:MM:SS PM');
otherwise
%the problem is here
mod_from=datestr(from,'dd/mm/yyyy HH:MM:SS PM');
end
end
Answers from 'the cyclist' and 'andrei' help me understood this better. THanks guys.

카테고리

도움말 센터File Exchange에서 Financial Toolbox에 대해 자세히 알아보기

질문:

2011년 12월 15일

Community Treasure Hunt

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

Start Hunting!

Translated by