Datestr problem with Hour

7 views (last 30 days)
Harold Kidder
Harold Kidder on 15 Jun 2014
Commented: dpb on 16 Jun 2014
I wrote a test routine to set a start time stamp and step through hours.
function HourlyDateTEST2()
dvec(1)=2014;
dvec(2)=06;
dvec(3)=15;
dvec(4)=21;
dvec(5)=00;
dvec(6)=00;
dateVal=datenum(dvec);
for ii = 1:7
datestr(dateVal, 'mm/dd/yyyy HH:MM:SS')
dateVal = dateVal + 1/24;
end;
end
The output looks like the following:
06/15/2014 21:00:00
06/15/2014 22:00:00
06/15/2014 23:00:00
06/15/2014 00:00:00
06/16/2014 01:00:00
06/16/2014 02:00:00
06/16/2014 03:00:00
Notice that the 4th line has the wrong date. Should be 06/16/2014 00:00:00.
What am I doing wrong?
I am using MATLAB R2014a.

Accepted Answer

Star Strider
Star Strider on 15 Jun 2014
That’s easiest with the addtodate function.
  13 Comments
Star Strider
Star Strider on 16 Jun 2014
I reported this a a bug to TMW yesterday. I got an e-mail a few minutes ago that said that they were able to reproduce it in R2014a, and will fix it ‘in a future release’. Whether this means an update or wait until R2014b I’m not sure. I sent them the link to this thread, so they have all the information they need.
Congratulations to Harold for discovering it!
dpb
dpb on 16 Jun 2014
I'd still be curious if you can generate the two cases to see the actual datenum values. You running 32- or 64-bit version?
I'm still greatly puzzled how can't now seem to reproduce it here when was certain saw it in the original loop version. I suppose I could have mistakenly thought I saw what I didn't.

Sign in to comment.

More Answers (1)

dpb
dpb on 15 Jun 2014
What am I doing wrong?
for ii = 1:7
datestr(dateVal, 'mm/dd/yyyy HH:MM:SS')
dateVal = dateVal + 1/24;
...
Using floating point arithmetic; the rounding in the accumulation of the 1/24 factor caused it.
Use
>> datestr(datenum(dvec(1),dvec(2),dvec(3),dvec(4)+[0:7].',dvec(5),dvec(6)))
ans =
15-Jun-2014 21:00:00
15-Jun-2014 22:00:00
15-Jun-2014 23:00:00
16-Jun-2014 00:00:00
16-Jun-2014 01:00:00
16-Jun-2014 02:00:00
16-Jun-2014 03:00:00
16-Jun-2014 04:00:00
>>
instead (add the integer hours, not the fractional days) to avoid rounding errors.

Categories

Find more on Dates and Time 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!