我正在使用timeIntervalSinceNow函数来确定某个时间和当前时间之间的差异。我使用了“ZeroFormattingBehaviour”来.DropAll来摆脱日期中的任何0。但是我想这样做,所以差异不包括秒差。例如,如果差异是2天,5小时,25分钟和40秒,我希望它只显示2天,5小时,25分钟。 (例如,排除秒部分)有没有办法这样做?
代码如下:
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Values")
let sortDescriptor = NSSortDescriptor(key: "time", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
do {
let results = try managedContext.executeFetchRequest(fetchRequest)
Values = results as! [NSManagedObject]
for result in results as! [NSManagedObject] {
times = result.valueForKey("time") as! String
let timeFormatter = NSDateFormatter()
timeFormatter.locale = NSLocale.currentLocale()
timeFormatter.dateFormat = "HH:mm dd/MM/yy"
let otherTime = timeFormatter.dateFromString(times)
let dateComponentsFormatter = NSDateComponentsFormatter()
dateComponentsFormatter.unitsStyle = NSDateComponentsFormatterUnitsStyle.Abbreviated
dateComponentsFormatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehavior.DropAll
let difference = otherTime?.timeIntervalSinceNow
let diffAbs = abs(difference!)
let stringDiff = dateComponentsFormatter.stringFromTimeInterval(diffAbs)
// "\n" skips a line in the text
TimerLabel.text = stringDiff!
}
} catch let error as NSError {
TimerLabel.text = "There seems to be an error. Please try again later"
print("Could not fetch \(error), \(error.userInfo)")
}
由于
答案 0 :(得分:0)
指定要显示的单位
dateComponentsFormatter.allowedUnits = [.Day, .Hour, .Minute]