Datenum comparison not behaving

1 回表示 (過去 30 日間)
Trevor Harris
Trevor Harris 2016 年 6 月 8 日
コメント済み: dpb 2016 年 6 月 8 日
Hi all,
So I feel like I must have a fundamental misunderstanding how datenum behaves. What I understood was that datenum assigned a value associated with a date, and that number will be ever increasing for future dates. I'm comparing the two dates below, (jan 13th and may 12th of this year), so presumably the datenum conversion of jan 13th will be less than that of may 12th. However, this does not seem to be the case. Please see the attached screenshot showing the behavior. Any ideas?
Thanks! Trevor

採用された回答

Jos (10584)
Jos (10584) 2016 年 6 月 8 日
MM refers to minutes rather than months ... Use the lower case format string!
datenum('20160113','yyyymmdd')
See the help of datestr for more info on the format symbols.

その他の回答 (4 件)

dpb
dpb 2016 年 6 月 8 日
編集済み: dpb 2016 年 6 月 8 日
Bad input format string... 'MM' is minutes, 'mm' is months...
>> datenum('20160113','yyyymmdd')<datenum('20160512','yyyymmdd')
ans =
1
>>
Read the format table in the documentation carefully; also note datenum uses a different encoding scheme than the new datetime class...

Star Strider
Star Strider 2016 年 6 月 8 日
Your date conversion format strings seem to be wrong.
Try this:
q1 = datenum('20160113','yyyymmdd');
q1a = datevec(q1)
q2 = datenum('20160512','yyyymmdd');
q2a = datevec(q2)
test = q1 < q2
q1a =
2016 1 13 0 0 0
q2a =
2016 5 12 0 0 0
test =
1
It is always a good idea to use datestr or datevec to be sure the conversion was correct.

Steven Lord
Steven Lord 2016 年 6 月 8 日
編集済み: Steven Lord 2016 年 6 月 8 日
If possible I recommend you use datetime rather than serial date numbers.
date1 = datetime(2016, 1, 13);
date2 = datetime('5/12/2016', 'InputFormat', 'MM/dd/yyyy');
isJan13BeforeMay12 = date1 < date2
You can perform operations on dates and times directly using datetime and display them without having to translate back and forth between numbers that are in the vicinity of 730000 and human-readable strings.
[And yes, datetime uses M in the format string to represent months and m to represent minutes while datestr which uses the reverse convention. This is mentioned in the documentation and is because datetime adheres to a Unicode standard (LDML) that I believe didn't exist yet when datestr was created.]

Trevor Harris
Trevor Harris 2016 年 6 月 8 日
Great, thanks for the help, guys. Lower case it is!!!
  1 件のコメント
dpb
dpb 2016 年 6 月 8 日
So ACCEPT an answer and give a "thumbs up" to the alternates...

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeDates and Time についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by