Datenum produces different values for the same date in different formats

3 Ansichten (letzte 30 Tage)
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?

Akzeptierte Antwort

dpb
dpb am 6 Dez. 2016
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 Kommentare
dpb
dpb am 6 Dez. 2016
Bearbeitet: dpb am 6 Dez. 2016
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 am 11 Dez. 2016
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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Dates and Time finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by