またはこれを試してください。 components:fromDate:
を使用してからcomponents:fromDateComponents:toDateComponents:options:
を使用する必要があることに注意してください。昨夜23:59でなければ、昨日の代わりに23:59を返します。
extension NSDateFormatter {
static func friendlyStringForDate(date:NSDate) -> String {
// Fetch the default calendar
let calendar = NSCalendar.currentCalendar()
// Compute components from target date
let from = calendar.components([.Day, .Month, .Year], fromDate: date)
// Compute components from current date
let to = calendar.components([.Day, .Month, .Year], fromDate: NSDate())
// Compute days difference between the two
let delta = calendar.components(.Day, fromDateComponents: from, toDateComponents: to, options: [])
switch delta.day {
case 0:
let formatter = NSDateFormatter()
formatter.timeZone = NSTimeZone.defaultTimeZone()
formatter.dateFormat = "HH:mm"
return formatter.stringFromDate(date)
case 1:
return "Yesterday"
case 2..<7:
let formatter = NSDateFormatter()
formatter.timeStyle = .NoStyle
formatter.dateFormat = "EEEE"
return formatter.stringFromDate(date)
default:
let formatter = NSDateFormatter()
formatter.timeStyle = .NoStyle
formatter.dateFormat = "MM/dd/YY"
return formatter.stringFromDate(date)
}
}
}
さて、ちょうどそれを使用します
timeLabel.text = NSDateFormatter.friendlyStringForDate(date!)
NsCalendarを見てみましょう、特にhttps://developer.apple.com/library/ NSCalendar_Class /#// apple_ref/occ/instm/NSCalendar/components:fromDate:toDate:options: –
'(最近の[日付]]?文字列)!これは、私は叫ぶ。 – EmilioPelaez
[iOSでのNSDateとの人間のフレンドリーな日付の記述]の可能な複製(http://stackoverflow.com/questions/6332298/human-friendly-date-descriptions-with-nsdate-on-ios) – kennytm