您可以使用 NSCalendar 方法 dateByAddingUnit:
func convertValueToDate(value: Float) -> NSDate {
struct Cal {
static let iso8601 = NSCalendar(identifier: NSCalendarIdentifierISO8601)!
}
let now = NSDate()
print("now: ", now)
switch(value) {
case 1:
print("5 years ago")
return Cal.iso8601.dateByAddingUnit(.Year, value: -5, toDate: now, options: [])!
case 2:
print("one year ago")
return Cal.iso8601.dateByAddingUnit(.Year, value: -1, toDate: now, options: [])!
case 3:
print("six months ago")
return Cal.iso8601.dateByAddingUnit(.Month, value: -6, toDate: now, options: [])!
case 4:
print("one month ago")
return Cal.iso8601.dateByAddingUnit(.Month, value: -1, toDate: now, options: [])!
case 5:
print("one week ago")
return Cal.iso8601.dateByAddingUnit(.WeekOfYear, value: -1, toDate: now, options: [])!
case 6:
print("yesterday")
return Cal.iso8601.dateByAddingUnit(.Day, value: -1, toDate: now, options: [])!
case 7:
print("today")
return now
default:
print("default date")
return now
}
}
如果您需要返回该日期的开始日期,您可以使用 NSCalendar startOfDayForDate 方法。
func convertValueToDate(value: Float) -> NSDate {
struct Cal {
static let iso8601 = NSCalendar(identifier: NSCalendarIdentifierISO8601)!
}
let now = NSDate()
print("now: ", now)
let result: NSDate
switch(value) {
case 1:
print("5 years ago")
result = Cal.iso8601.dateByAddingUnit(.Year, value: -5, toDate: now, options: [])!
case 2:
print("one year ago")
result = Cal.iso8601.dateByAddingUnit(.Year, value: -1, toDate: now, options: [])!
case 3:
print("six months ago")
result = Cal.iso8601.dateByAddingUnit(.Month, value: -6, toDate: now, options: [])!
case 4:
print("one month ago")
result = Cal.iso8601.dateByAddingUnit(.Month, value: -1, toDate: now, options: [])!
case 5:
print("one week ago")
result = Cal.iso8601.dateByAddingUnit(.WeekOfYear, value: -1, toDate: now, options: [])!
case 6:
print("yesterday")
result = Cal.iso8601.dateByAddingUnit(.Day, value: -1, toDate: now, options: [])!
case 7:
print("today")
result = now
default:
print("default date")
result = now
}
return Cal.iso8601.startOfDayForDate(result)
}