2017-05-18 154 views
0

我想在MATLAB中將83012(一個int)轉換爲'8:30:12'(一個字符串)。我找不到明確的答案。真正的問題是添加冒號。任何幫助表示讚賞。在Matlab中將數字轉換爲實際時間字符串

%Get the start time value from User 
str1  = get(handles.StartEditTag, 'string'); 
newstr1 = erase(str1, ':'); %Take out colons (eg '6:30:00' -> '63000') 
startVal = str2num(newstr1); %Convert string to num (eg '63000' -> 63000) 

%Get the end time value from the User 
str2 = get(handles.EndEditTag, 'string'); 
newstr2 = erase(str2, ':'); 
endVal = str2num(newstr2); 

roundStart = mod(startVal, 100); %(eg 63000 -> 00) 
roundEnd = mod(endVal, 100); 

if mod(roundStart, 15) ~= 0 
    %Round to the nearest multiple of 15 (eg 83027 -> 83030) 
    startVal = Roundto15(roundStart, startVal); %function I made to round 
end 

if mod(roundEnd, 15) ~= 0 
    endVal = Roundto15(roundEnd, endVal); 
end 

startString = int2str(startVal); %(eg 83030 -> '83030') 
endString = int2str(endVal); 

我正在從用戶的時間間隔,並確保它是每隔15秒。這是我迄今爲止所擁有的。

+0

這似乎很容易。顯示你的代碼,有人會很快告訴你如何添加冒號 –

+0

剛剛發佈了我的。 – Matt

回答

3

假設你的整數總是有5個或6位數字

time_int=83012; 
time_str=num2str(time_int); 
result=strcat(time_str(1:end-4),':',time_str(end-3:end-2),':',time_str(end-1:end)); 

編輯:一更好的方式來做整件事

% The string you get from the user 
str1 = '16:30:12'; 

% Extraing hours, minutes, seconds 
C1 = textscan(str1,'%d:%d:%d'); 

% converting the time to seconds 
time1_in_seconds = double((C1{1}*3600)+(C1{2}*60)+C1{3}); 

% rounding to 15 sec 
time1_in_seconds_round15 = round(time1_in_seconds/15)*15; 

% getting the new hours, minutes and seconds 
hours = floor(time1_in_seconds_round15/3600); 
minutes = floor((time1_in_seconds_round15 - hours*3600)/60); 
seconds = time1_in_seconds_round15 - hours*3600 - minutes*60; 

% getting the string 
s = sprintf('%d:%d:%d', hours, minutes, seconds); 
1

首先做你的算術計算小時,分鐘和秒,然後用字符串格式化:

s = sprintf('%d:%02d:%02d', hours, minutes, seconds) 
相關問題