Validation of a date with a given format
古いコメントを表示
Hi. I am designing a GUI. I have an edit text box where I enter a date string with the following format '31 Mar 2011 10:00:00.000'. I need code to validate it and write an error message in case of invalid input. Thank you for your attention. Cheers.
採用された回答
その他の回答 (3 件)
Matt Fig
2011 年 4 月 14 日
try
D = datenum(Inpt,'dd mmm yyyy HH:MM:SS.FFF')
catch
error('Incorrect Format')
end
4 件のコメント
Matt Tearle
2011 年 4 月 14 日
Great minds may think alike, but apparently one types faster than the other :)
Matt Fig
2011 年 4 月 14 日
I guess so! The only problem with our approach is that Julian may want to be more pedantic than we would be. For example, the user doesn't have to enter exactly 3 places for the millisecond data. If Julian wants this then there will have to be further checks. This would pass our tests:
31 Mar 2011 10:00:00.0
Julián Francisco
2011 年 4 月 15 日
Matt Fig
2011 年 4 月 15 日
I wasn't saying you _were_ pedantic, only that as far as I know, you _might_ want to the user to enter in exactly 3 values for the milliseconds position. If you don't care about this, then the code should work fine if the user enters only one value. All else will be checked as you requested....
Matt Tearle
2011 年 4 月 14 日
fmt = 'dd mmm yyyy HH:MM:SS.FFF';
dt = [];
while isempty(dt)
x = input(['enter date string in ',fmt,' format: '],'s');
try
dt = datenum(x,fmt);
catch
disp(['Hey idiot, I said ',fmt,' format'])
end
end
(Obviously I'm using input in place of the GUI entry, but the basic structure/flow would be the same)
Walter Roberson
2011 年 4 月 14 日
% 31 Mar 2011 10:00:00.000
Basic validation:
regexp(t, '[0-3]\d (Jan|Feb|Mar|...|Dec) \d\d\d\d (0\d|1[0-2]):[0-5]\d:[0-5]\d.\d\d\d')
Once you've done the basic validation, you can cross-check for consistency such as the maximum day number being appropriate for the month.
3 件のコメント
Jan
2011 年 4 月 15 日
Matlab's date functions check the validity sufficiently. If the date string is valid, DaTESTR(DATENUM(STR)) equals STR.
Julián Francisco
2011 年 4 月 15 日
Julián Francisco
2011 年 4 月 15 日
カテゴリ
ヘルプ センター および File Exchange で Dates and Time についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!