とりあえず以下をPlayground
に貼り付けて動きを確認してみてください。
※ 細かい動作確認はしてません。
swift
1let startDate = NSDate()
2let endDate = NSDate(timeIntervalSinceNow: (60 * 60 * 24 * 400))
3
4// 60 * 60 * 24 * 400 => 1年1月4日
5// 60 * 60 * 24 * 50 => 50日前
6// 60 * 60 => 1時間前
7// 60 => 1分前
8// 59 => 59秒前
9
10
11let cal = NSCalendar.currentCalendar()
12
13let unitFlags1: NSCalendarUnit = [.Year, .Month, .Day, .Hour, .Minute, .Second]
14let unitFlags2: NSCalendarUnit = [.Day]
15let components1 = cal.components(unitFlags1, fromDate: startDate, toDate: endDate, options: NSCalendarOptions())
16let components2 = cal.components(unitFlags2, fromDate: startDate, toDate: endDate, options: NSCalendarOptions())
17
18var result = ""
19if components1.year > 0 {
20 result = String(components1.year) + "年" + String(components1.month) + "月" + String(components1.day) + "日"
21} else if components1.month > 0 || components1.day > 0 {
22 result = String(components2.day) + "日前"
23} else if components1.hour > 0 {
24 result = String(components1.hour) + "時間前"
25} else if components1.minute > 0 {
26 result = String(components1.minute) + "分前"
27} else {
28 result = String(components1.second) + "秒前"
29}
30
31result
32//=> 結果出力
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/08/24 04:41