swift 时间友好提示

Posted by Roy on 2017-04-05
323字预计2分

废话不多直接上代码

备注 NSLocalizedString()是国际化支持

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//
// TimeAgo.swift
// TimeAgo
//
// Created by roycms on 2017/3/15.
// Copyright © 2017年 北京三芳科技有限公司. All rights reserved.
//
import Foundation
public extension NSDate {
public func ago() -> String {
return funTimeAgo(self as Date)
}
public var timeAgo:String{
get{
return funTimeAgo(self as Date)
}
}
}
public extension Double {
public func ago() -> String {
return funStampTimeAgo(self as Double)
}
public var timeAgo:String{
get{
return funStampTimeAgo(self as Double)
}
}
}
func funStampTimeAgo(_ date: Double) -> String{
return funTimeAgo(NSDate(timeIntervalSince1970: TimeInterval(date)) as Date)
}
func funTimeAgo(_ date: Date) -> String {
let calendar = Calendar.current
let now = Date()
let unitFlags: NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfYear, .month, .year]
let components = (calendar as NSCalendar).components(unitFlags, from: date, to: now, options: [])
if let year = components.year, year >= 2 {
return "\(year) " + NSLocalizedString("yearsAgo",comment:"years ago")
}
if let year = components.year, year >= 1 {
return NSLocalizedString("LastYear",comment:"Last year")
}
if let month = components.month, month >= 2 {
return "\(month) " + NSLocalizedString("monthsAgo",comment:"months ago")
}
if let month = components.month, month >= 1 {
return NSLocalizedString("LastMonth",comment:"Last month")
}
if let week = components.weekOfYear, week >= 2 {
return "\(week) " + NSLocalizedString("weeksAgo",comment:"weeks ago")
}
if let week = components.weekOfYear, week >= 1 {
return NSLocalizedString("LastWeek",comment:"Last week")
}
if let day = components.day, day >= 2 {
return "\(day) " + NSLocalizedString("daysAgo",comment:"days ago")
}
if let day = components.day, day >= 1 {
return NSLocalizedString("Yesterday",comment:"Yesterday")
}
if let hour = components.hour, hour >= 2 {
return "\(hour) " + NSLocalizedString("hoursAgo",comment:"hours ago")
}
if let hour = components.hour, hour >= 1 {
return NSLocalizedString("AnHourAgo",comment:"An hour ago")
}
if let minute = components.minute, minute >= 2 {
return "\(minute) " + NSLocalizedString("minutesAgo",comment:"minutes ago")
}
if let minute = components.minute, minute >= 1 {
return NSLocalizedString("AMinuteAgo",comment:"A minute ago")
}
if let second = components.second, second >= 3 {
return "\(second) " + NSLocalizedString("secondsAgo",comment:"seconds ago")
}
return NSLocalizedString("JustNow",comment:"Just now")
}

Kommentare: