몇시간전
몇분전
등등...
이런 정보를 표시해야 하는 경우가 있다.
NSDate의 extension으로 다음과 같이 구현 한다음
이를 이용하면 가능 하다.
import Foundation
extension NSDate {
func yearsFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(.Year, fromDate: date, toDate: self, options: []).year
}
func monthsFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(.Month, fromDate: date, toDate: self, options: []).month
}
func weeksFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(.WeekOfYear, fromDate: date, toDate: self, options: []).weekOfYear
}
func daysFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(.Day, fromDate: date, toDate: self, options: []).day
}
func hoursFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(.Hour, fromDate: date, toDate: self, options: []).hour
}
func minutesFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(.Minute, fromDate: date, toDate: self, options: []).minute
}
func secondsFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(.Second, fromDate: date, toDate: self, options: []).second
}
func offsetFrom(date:NSDate) -> String {
if yearsFrom(date) > 0 { return "\(yearsFrom(date))y" }
if monthsFrom(date) > 0 { return "\(monthsFrom(date))M" }
if weeksFrom(date) > 0 { return "\(weeksFrom(date))w" }
if daysFrom(date) > 0 { return "\(daysFrom(date))d" }
if hoursFrom(date) > 0 { return "\(hoursFrom(date))h" }
if minutesFrom(date) > 0 { return "\(minutesFrom(date))m" }
if secondsFrom(date) > 0 { return "\(secondsFrom(date))s" }
return ""
}
}
사용하는 방법은 다음과 같다.
lastSportData.year, mont, day 값을 NSDate로 만들어서 현재 NSDate와의 몇일 차이인지 문자열을 만든다.
let date = NSDate()
let day = date.daysFrom(makedate(lastSportData.year, month: lastSportData.month, day: lastSportData.day))
if day > 0 {
agoLabel.text = "\(day)days ago"
} else {
agoLabel.text = "today"
}
댓글 없음:
댓글 쓰기