我使用 timeIntervalSinceNow 函数来确定特定时间与当前时间之间的差异。我已使用 .DropAll 的“ZeroFormattingBehaviour”来删除日期中的任何 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)")
}
谢谢
最佳答案
指定要显示的单位
dateComponentsFormatter.allowedUnits = [.Day, .Hour, .Minute]
关于Swift - timeIntervalSinceNow 只想显示分钟(不包括秒部分),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34886911/