How to display datetime() value up to milliseconds - matlab

I have two questions:
In the following MATLAB code x is a date time value of the format "datetime(Y,M,D,H,MI,S,MS)". The display(x) command displays '00:00:00'. However the 'if condition' displays 'Well received!' which means the real value of x is greater than 0 as opposed to '00:00:00' displayed by the display(x) command. Please suggest how I could display the full value of x up to milliseconds or microseconds.
How can I save '0000,00,00,00,00,00,200' as a date time value?
send = datetime(2016,08,31,06,01,00,00);
receive=datetime(2016,08,31,06,01,00,100);
x=receive-send;
display(x);
if (x>0)
disp('Well received!')
else
disp('Late!')
end

The solution of your first question is, that you might convert your datetime-variable to a formatted string:
disp(datestr(x,'HH:MM:SS:FFF'));
This gives you the output 00:00:00:100, because F is the symbolic identifier for milliseconds.
Furthermore it seems, datetime doesn't support milliseconds. In this case you should use the MATLAB serial date number:
http://de.mathworks.com/help/matlab/ref/datenum.html

The variable x created in your example is a duration object. You can specify the display of milliseconds (as well as smaller decimal fractions of seconds) by setting the Format property.
>> x.Format = 'hh:mm:ss.SSS';
>> display(x);
x = 00:00:00.100
This is presumably also what you want when you ask about saving '0000,00,00,00,00,00,200' as a date time value. It's not really a date and time but a duration, and can be created using the duration constructor.
>> duration(00,00,00,200,'Format','hh:mm:ss.SSS')
ans =
00:00:00.200
Most operations acting on these duration objects will work as expected, such as comparison with the > operator:
>> x > duration(00,00,00,200)
ans =
0

Related

method for converting seconds from date to datetime

Is there a method in matlab to convert seconds from a known date to a standard date time format?
For example, if I have a vector of values shown as seconds from 1901/01/01, how would I convert them to a dateTime? In this case a value of 28125 would correspond to 1981/01/01. Is there an efficient method for doing this?
The numbers in your example do not make sense so it is not clear if your time is in seconds or days but since you asked for seconds I will use this.
What you want to achieve can be done using datenum function. This function returns the number of (fractional) days from 1/1/0000. So first you need to find your offset, e.g.:
offsetInDays = datenum(1901,1,1);
Next, you convert the date from seconds to days:
dateInDays = YourRequiredDateInSec * 3600 * 24;
Finally, you date is given by
RequiredDate = datestr(offsetInDays + dateInDays);

Converting time to milliseconds?

I have some time as string format in my data. Can anyone help me to convert this date to milliseconds in Matlab.
This is an example how date looks like '00:26:16:926', So, that is 0 hours 26 minutes 16 seconds and 926 milliseconds. After converting this time, I need to get only milliseconds such as 1576926 milliseconds for the time that I gave above. Thank you in advance.
Why don't you try using datevec instead? datevec is designed to take in various time and date strings and it parses the string and spits out useful information for you. There's no need to use regexp or split up your string in any way. Here's a quick example:
[~,~,~,hours,minutes,seconds] = datevec('00:26:16:926', 'HH:MM:SS:FFF');
out = 1000*(3600*hours + 60*minutes + seconds);
out =
1576926
In this format, the output of datevec will be a 6 element vector which outputs the year, month, day, hours, minutes and seconds respectively. The millisecond resolution will be added on to the sixth element of datevec's output, so all you have to do is convert the fourth to sixth elements into milliseconds and add them all up, which is what is done above. If you don't specify the actual day, it just defaults to January 1st of the current year... but we're not using the date anyway... we just want the time!
The beauty with datevec is that it can accept multiple strings so you're not just limited to a single input. Simply put all of your strings into a single cell array, then use datevec in the following way:
times = {'00:26:16:926','00:27:16:926', '00:28:16:926'};
[~,~,~,hours,minutes,seconds] = datevec(times, 'HH:MM:SS:FFF');
out = 1000*(3600*hours + 60*minutes + seconds);
out =
1576926
1636926
1696926
One solution could be:
timeString = '00:26:16:926';
cellfun(#(x)str2num(x),regexp(timeString,':','split'))*[3600000;60000;1000;1]
Result:
1576926
Assuming that your date string comes in that format consistently, you could use something as simple as this:
test = '00:26:16:926';
H = str2num(test(1:2)); % hours
M = str2num(test(4:5)); % minutes
S = str2num(test(7:8)); % seconds
MS = str2num(test(10:12)); % milliseconds
totalMS = MS + 1000*S + 1000*60*M + 1000*60*60*H;
Output:
1576926.00
you can convert a single string with a date or even a vector by using datevec for conversion and the dot product
a = ['00:26:16:926' ; '08:42:12:936']
datevec(a,'HH:MM:SS:FFF') * [0 0 0 3600e3 60e3 1e3]'
ans =
1576926
31332936

Convert numerous date and time values into serial number

I need to convert date and time into a numerical value. for example:
>> num = datenum('2011-05-07 11:52:23')
num =
7.3463e+05
How would I write a script to do this for numerous values without inputting the date and time manually?
You can store your date strings first in a cell array (or a matrix, provided they are of fixed format), and feed it straight to datenum. For example:
C = {'2011-05-07 11:52:23'
'2011-03-01 20:30:01'};
vals = datenum(C)

Vectorising Date Array Calculations

I simply want to generate a series of dates 1 year apart from today.
I tried this
CurveLength=30;
t=zeros(CurveLength);
t(1)=datestr(today);
x=2:CurveLength-1;
t=addtodate(t(1),x,'year');
I am getting two errors so far?
??? In an assignment A(I) = B, the number of elements in B and
Which I am guessing is related to the fact that the date is a string, but when I modified the string to be the same length as the date dd-mmm-yyyy i.e. 11 letters I still get the same error.
Lsstly I get the error
??? Error using ==> addtodate at 45
Quantity must be a numeric scalar.
Which seems to suggest that the function can't be vectorised? If this is true is there anyway to tell in advance which functions can be vectorised and which can not?
To add n years to a date x, you do this:
y = addtodate(x, n, 'year');
However, addtodate requires the following:
x must be a scalar number, not a string.
n must be a scalar number, not a vector.
Hence the errors you get.
I suggest you use a loop to do this:
CurveLength = 30;
t = zeros(CurveLength, 1);
t(1) = today; % # Whatever today equals to...
for ii = 2:CurveLength
t(ii) = addtodate(t(1), ii - 1, 'year');
end
Now that you have all your date values, you can convert it to strings with:
datestr(t);
And here's a neat one-liner using arrayfun;
datestr(arrayfun(#(n)addtodate(today, n, 'year'), 0:CurveLength))
If you're sequence has a constant known start, you can use datenum in the following way:
t = datenum( startYear:endYear, 1, 1)
This works fine also with months, days, hours etc. as long as the sequence doesn't run into negative numbers (like 1:-1:-10). Then months and days behave in a non-standard way.
Here a solution without a loop (possibly faster):
CurveLength=30;
t=datevec(repmat(now(),CurveLength,1));
x=[0:CurveLength-1]';
t(:,1)=t(:,1)+x;
t=datestr(t)
datevec splits the date into six columns [year, month, day, hour, min, sec]. So if you want to change e.g. the year you can just add or subtract from it.
If you want to change the month just add to t(:,2). You can even add numbers > 12 to the month and it will increase the year and month correctly if you transfer it back to a datenum or datestr.

MATLAB result is inappropriate

I'm new in MATLAB, i cannot get the answer in the format that i want.
I have a basic function call, but every execution of the program gives the result in the following format :
357341279027200000/23794118819840001
It's supposed to be in decimal, for example for same execution : 15.0181.
I could not figure out why this is happening ? Can you help me, thank you !!
Type format long on the command prompt or in your script.
If that doesnt work because the value is too large, try using vpa
Note that it's just visual, internally the value computed is precise.
>d = 357341279027200000/23794118819840001
d =
15.0181
>> d * 23794118819840001 == 357341279027200000
ans =
1
>> 15.0181 * 23794118819840001 == 357341279027200000
ans =
0
Are you sure that you are not using format rat (rational). This is the reason why you may be having fractional values. If you want decimals, try format long or format long g (Long g provides the optimal length and accuracy as a decimal, up to 10 places.)