我有一个计算经过时间的日期,如下所示:
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [.hour, .minute, .second]
dateComponentsFormatter.unitsStyle = .positional
dateComponentsFormatter.zeroFormattingBehavior = .pad
if let timeElapsed = dateComponentsFormatter.string(from: startTime, to: Date()) {
timerLabel.text = timeElapsed
}
如果过了五秒钟,它会填充所有零,使字符串显示0:00:05
。但是,我希望让它说0:05
五秒钟,10:05
表示10分钟和5秒钟,1:10:05
表示1小时10分钟和5秒钟。我怎么能这样做?
答案 0 :(得分:0)
你可以计算字符数小于等于2然后提前追加等于这样=> “0:”+ timeElapsed
autoCompleteText.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View arg1, int position, long arg3) {
YourCustomModel YourFilterdSelectedModel = (YourCustomModel) adapterView.getItemAtPosition(position);
autoCompleteText.setText(str);
}
});
<强>输出强>
var totalTime = ""
let startTime = Date().addingTimeInterval(-50)
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [.hour, .minute, .second]
dateComponentsFormatter.unitsStyle = .positional
dateComponentsFormatter.zeroFormattingBehavior = .dropLeading
if let timeElapsed = dateComponentsFormatter.string(from: startTime, to: Date()) {
if timeElapsed.count <= 2 {
totalTime = "0:" + timeElapsed
}else {
totalTime = timeElapsed
}
print(totalTime)
}