我可以在日期选择器中获取日期,计算剩余时间并放入标签。这给了秒:
let timeLeft = datePicker.dateValue.timeIntervalSinceNow
countingLabel.stringValue = "seconds left: \(timeLeft)"
如何格式化“timeLeft”?
I tried this and it does not work:
var formatter = NSDateFormatter()
formatter.dateFormat = "EEEE, yyyy-MM-dd hh:mm:ss"
let timeLeft2 = formatter.stringFromDate(timeLeft)
答案 0 :(得分:4)
您可以使用NSDateComponentsFormatter
。来自
文档:
NSDateComponentsFormatter
对象需要花费大量时间和 将它们格式化为用户可读的字符串。使用日期组件 formatter为您的应用程序界面创建字符串。
示例:
let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = .Full
formatter.allowedUnits = .CalendarUnitSecond | .CalendarUnitMinute | .CalendarUnitHour
let pickedDate = datePicker.dateValue
let now = NSDate()
let formattedTimeLeft = formatter.stringFromDate(now, toDate: pickedDate)!
// Example result : 1:06:50
还有一些可用的输出格式,例如
.Abbreviated : 1h 6m 50s
.Short : 1 hr, 6 min, 50 secs
.Full : 1 hour, 6 minutes and 50 seconds
答案 1 :(得分:0)
要获得timeLeft,您应该使用两个时间组件并获得如下差异:
let todayComponents = NSCalendar.currentCalendar().components(.DayCalendarUnit | .MonthCalendarUnit | .YearCalendarUnit | .CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond | , fromDate : NSDate())
var pickedDateComponents = NSCalendar.currentCalendar().components(.DayCalendarUnit | .MonthCalendarUnit | .YearCalendarUnit | .CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond | , fromDate : datePicker.dateValue)
pickedDateComponents.second = pickedDateComponents.second - todayComponents.second
pickedDateComponents.minute = pickedDateComponents.minute - todayComponents.minute
pickedDateComponents.hour = pickedDateComponents.hour - todayComponents.hour
pickedDateComponents.day =pickedDateComponents.day - todayComponents.day
pickedDateComponents.month = pickedDateComponents.month - todayComponents.month
pickedDateComponents.year = pickedDateComponents.year - todayComponents.year
let timeLeft = NSCalendar.currentCalendar().dateFromComponents(pickedDateComponents)!