detestr/datenum behavior on Jan 1st.
Show older comments
I am going crazy. Please someone explain why this behavior occurs with dates on the 1st of Jan.
Here I want the MATLAB serial date associated with Jan 1, 2017 at mid-night:
datestr(datenum(2017,0,0,0,0,0))
ans =
31-Dec-2016
Ok so maybe this makes sense if you think of Midnight as part of the previous day. But I don't know many people who do. So what about an hour later:
datestr(datenum(2017,0,0,1,0,0))
ans =
31-Dec-2016 01:00:00
This result seems just plain wrong.
Interestingly MATLAB doesn't distinguish between a 0 or 1 to indicate January:
datestr(datenum(2017,1,0,1,0,0))
ans =
31-Dec-2016 01:00:00
In all of these cases, why does datestr() return a date on the previous day? What am I missing?
-Val
Accepted Answer
More Answers (1)
Steven Lord
on 7 Mar 2017
January 0th is December 31st. This isn't just a MATLAB convention.
One way to represent January 1st, 2017 as a datetime (which you should use instead of serial date numbers if they're available) is:
dt = datetime(2017, 1, 1, 0, 0, 0)
Another way that refers to the start of the current year:
T = datetime('today');
dt = dateshift(T, 'start', 'year');
To customize the display format to clearly show that dt (as defined by either of those lines of code) refers to midnight on January 1st:
dt.Format = 'dd-MMM-yyyy hh:mm:ss a'
Categories
Find more on Time Series Objects in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!