Effacer les filtres
Effacer les filtres

How to compare datenum variables

6 vues (au cours des 30 derniers jours)
Giovanni
Giovanni le 19 Sep 2011
Hello,
I have the following problem. I should compare some timestamps I have read from an excel file. Basically what I do is creating a vector containing this timestamps converted using the "datenum" command. If i then for example try to visualize the value of the variable, I get the following result on the console:
datenum(textdata{1})
ans =
7.3450e+005
>> datestr(ans)
ans =
01-Jan-2011 00:00:06
until this point I get it perfectly.
Now, if I have another timestamp which is for example:
01-Jan-2011 00:00:01
and I convert it to a numdate, i get the same result due to the precision which matlab uses to visualize my variable:
datenum(textdata2{1})
ans =
7.3450e+005
now if I wanna compare them, I was guessin, I can just make a simple if test:
a = 01-Jan-2011 00:00:06; b = 01-Jan-2011 00:00:01;
if a == b disp ('equal') elseif a > b disp ('greater') else disp('smaller') end
greater
So up to this point is everything ok.
After that i increase b of the right quantity to make it the same as a:
b = b + (5/(3600*24)); %now b is 01-Jan-2011 00:00:06;
if a == b disp ('equal') elseif a > b disp ('greater') else disp('smaller') end
smaller
What is happening here? why I don´t get that they are the same? For instance this test gives me 'equal' only if I directly assign a = b.
How can I manage this situation?

Réponse acceptée

Jan
Jan le 19 Sep 2011
DATENUM creates a numerical representation of the date with high accuracy, only the display in the command window is abbreviated:
datenum('01-Jan-2011 00:00:01')
>> 7.3450e+005
format long g
datenum('01-Jan-2011 00:00:01')
>> 734504.000011574
See format.
If you convert the date to a string, adding a numerical value is not valid. For a serial date number adding a numerical value is accompanied by rounding, e.g. as in 0.1+0.2~=0.3, see FAQ: Limited precision.
date1 = datenum('01-Jan-2011 00:00:01');
date2 = datenum('01-Jan-2011 00:00:06');
date2 - (date1 + 5/86400)
% >> -1.16415321826935e-010
In consequence arithmetical operations with dates are more accurately performed in datevec format. And a comparison of date strings is done by strcmp.

Plus de réponses (0)

Catégories

En savoir plus sur Dates and Time dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by