我想将83012(一个整数)转换为' 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 :(得分: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 :(得分:1)
首先进行算术计算小时,分钟和秒,然后使用字符串格式:
s = sprintf('%d:%02d:%02d', hours, minutes, seconds)