Datenum produces different values for the same date in different formats

조회 수: 3 (최근 30일)
Bryan
Bryan 2016년 12월 6일
댓글: Peter Perkins 2016년 12월 11일
I've noticed that the datenum function produces two different values for the same date (9/28/2006) when the arguments are in different formats. The difference in this example is significant: 243 days.
datenum(2006,9,28)
ans =
732948
but
datenum('20060928','YYYYMMDD')
ans =
732705.00625
Why is this?

채택된 답변

dpb
dpb 2016년 12월 6일
Because the datenum/datestr month,day,year format string values are lower case, not upper. You converted the string representation into
>> datestr(datenum('20060928','YYYYMMDD'))
ans =
28-Jan-2006 00:09:00
>>
9 minutes into the 28th day of of 2006. OTOH,
>> datestr(datenum('20060928','yyyymmdd'))
ans =
28-Sep-2006
>>
It's somewhat of a poor quality of implementation issue in my view that the YYYY and yyyy are accepted interchangeably; if it erred on that it would give the clue of "you really mean that???!!!" instead of the silent return of an unexpected result.
  댓글 수: 3
dpb
dpb 2016년 12월 6일
편집: dpb 2016년 12월 6일
It only really matters for m and M, but since they're the same letter of the alphabet for two different fields they must be case-sensitive. That the input parser isn't for the non-overlapping fields makes it easier to make a mistake.
What's then really confusing is that the abbreviations are entirely different (and in some cases, conflicting in meaning) for the new datetime class (albeit they now follow an international Standard so there's a valid reason for the change).
Peter Perkins
Peter Perkins 2016년 12월 11일
Also: if you'd done the corresponding thing with datetime, you'd have been warned:
>> datetime('20060928','InputFormat','yyyymmdd')
Warning: The format 'yyyymmdd' contains a field for minute (m) in what appears to be a date portion. You might have
intended to use the symbol for month (M) rather than for minute (m). See the datetime.Format property for a complete
description of the identifiers used in format character vectors.
> In verifyFormat (line 20)
In datetime (line 604)
ans =
datetime
28-Jan-2006 00:09:00
And also, datetime has a built-in conversion from numeric values like 20060928, preventing the whole issue:
>> datetime(20060928,'ConvertFrom','yyyymmdd')
ans =
datetime
28-Sep-2006 00:00:00

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by