Reputation: 379
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.
Upvotes: 2
Views: 4067
Reputation: 7043
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
Upvotes: -1
Reputation: 104565
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
Upvotes: 5
Reputation: 2180
One solution could be:
timeString = '00:26:16:926';
cellfun(@(x)str2num(x),regexp(timeString,':','split'))*[3600000;60000;1000;1]
Result:
1576926
Upvotes: 5
Reputation: 4471
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
Upvotes: 1