自定义日期组件的自定义零格式化行为

时间:2018-04-06 11:33:12

标签: ios swift

我有一个计算经过时间的日期,如下所示:

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秒钟。我怎么能这样做?

1 个答案:

答案 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)
}