SwiftDate
是Github上开源的,使用Swift语言编写的NSDate封装库,可以很方便的在Swift中处理日期,比如日期创建,比较,输出等。
特性
http://www.cnblogs.com/QianChia/p/5777454.html
- 支持数学运算符进行日期计算(比如myDate + 2.week + 1.hour)
- 支持比较运算符(比如<,>,==,<=,>=)
- 快速获取/修改日期各部分内容(比如获取或修改日期中的月份)
- 提供通用格式化输出或自定义的格式化输出
- 提供一系列.toString方法
- 提供简便的方法获取yesterday,tomorrow等
依赖
- iOS 8.0+ / Mac OS X 10.10+
- Xcode 6.3+
- Swift 1.2
使用
CocoaPods安装SwiftDate
我们需要通过CocoaPods安装SwitDate,如果你还没有安装cocoapods,可以通过如下命令安装
$ gem install cocoapods
然后在你的Xcode项目中的Podfile文件中,添加如下内容:
- source 'https://github.com/CocoaPods/Specs.git'
- platform :ios, '8.0'
- use_frameworks!
-
- pod 'SwiftDate'
最后,执行如下命令安装
$ pod install
创建日期
- 通过解析字符串创建
let date_custom = NSDate.date(fromString: "2015-07-26", format: DateFormat.Custom("YYYY-MM-DD"))
1、NSDate 的创建
// 当前时间值,GMT 时间
let date1:NSDate = NSDate()
// 当前时间加 n 秒后的值
let date2:NSDate = NSDate(timeIntervalSinceNow: 10)
// 某个时间增加 n 秒后的值
let date3:NSDate = NSDate(timeInterval: 10, sinceDate: date2)
// 从 1970-01-01 00:00:00 (GMT) 增加 n 秒后的值
let date4:NSDate = NSDate(timeIntervalSince1970: 3600)
// 从 2001-01-01 00:00:00 (GMT) 增加 n 秒后的值
let date5:NSDate = NSDate(timeIntervalSinceReferenceDate: 10)
// 未来某一个随机时间
let date6:NSDate = NSDate.distantFuture()
// 过去某一个随机时间
let date7:NSDate = NSDate.distantPast()
// 某个时间增加 n 秒后的值
let date8:NSDate = date5.dateByAddingTimeInterval(20)
- 通过指定日期各部分创建
let date_from_components = NSDate.date(refDate: nil, year: 2014, month: 01, day: nil, hour: nil, minute: nil, second: nil, tz: "
UTC")
2、NSDate 时间间隔的计算
let date1 = NSDate()
let date2 = date1.dateByAddingTimeInterval(20)
// 实例保存的时间 与 当前时间 的时间间隔,单位 秒
let interval1:NSTimeInterval = date2.timeIntervalSinceNow
// 实例保存的时间 与 指定时间 的时间间隔,单位 秒
let interval2:NSTimeInterval = date2.timeIntervalSinceDate(date1)
// 实例保存的时间 与 1970-01-01 00:00:00 (GMT) 的时间间隔,单位 秒
let interval3:NSTimeInterval = date1.timeIntervalSince1970
// 实例保存的时间 与 2001-01-01 00:00:00 (GMT) 的时间间隔,单位 秒
let interval4:NSTimeInterval = date1.timeIntervalSinceReferenceDate
// 当前时间 与 2001-01-01 00:00:00 (GMT) 的时间间隔,单位 秒
let interval5:NSTimeInterval = NSDate.timeIntervalSinceReferenceDate()
3、NSDate 时间的比较
let date1 = NSDate()
let date2 = date1.dateByAddingTimeInterval(20)
// 判断两个时间是否相等
let bl:Bool = date1.isEqualToDate(date2)
// 比较两个时间大小
let result:NSComparisonResult = date1.compare(date2)
// 比较两个时间,返回 较早的时间
let date3 = date1.earlierDate(date2)
// 比较两个时间,返回 较晚的时间
let date4 = date1.laterDate(date2)
4、时区差值转换
// 得到当前时间(世界标准时间 UTC/GMT)
var date:NSDate = NSDate()
// 设置系统时区为本地时区
let zone:NSTimeZone = NSTimeZone.systemTimeZone()
// 计算本地时区与 GMT 时区的时间差
let second:Int = zone.secondsFromGMT
// 在 GMT 时间基础上追加时间差值,得到本地时间
date = date.dateByAddingTimeInterval(NSTimeInterval(second))
5、NSDateComponents 的创建
// 由手动设置创建
let compt1:NSDateComponents = NSDateComponents()
// 日历
compt1.calendar = NSCalendar.currentCalendar()
// 时区
compt1.timeZone = NSTimeZone.systemTimeZone()
compt1.era = 1 // 纪元
compt1.year = 2016 // 年
compt1.month = 3 // 月
compt1.day = 1 // 日
compt1.hour = 10 // 时
compt1.minute = 12 // 分
compt1.second = 55 // 秒
compt1.nanosecond = 280 // 微妙
compt1.quarter = 0 // 刻钟
compt1.weekday = 3 // 周几
compt1.weekdayOrdinal = 1 // 指定日期为本月的第几个星期几
compt1.weekOfMonth = 1 // 指定日期为本月的第几周
compt1.weekOfYear = 10 // 指定日期为本年的第几周
compt1.yearForWeekOfYear = 2016 //
// 由已知 date 创建
/*
只有明确指定了 unitFlags,NSDateComponents 相应的那一部分才有值。在 Swift 2.2 中不能使用 “|” 连接两个 Unit 枚举值
*/
let flag:NSCalendarUnit = [.Era, .Year, .Month, .Day, .Hour, .Minute, .Second, .Nanosecond, .Quarter, .Weekday,
.WeekdayOrdinal, .WeekOfMonth, .WeekOfYear, .WeekOfYear, .Calendar, .TimeZone]
let compt2:NSDateComponents = NSCalendar.currentCalendar().components(flag, fromDate: NSDate())
6、NSDateComponents 时间间隔的计算
let date1:NSDate = NSDate()
let date2:NSDate = NSDate(timeInterval: 5*60*60+75, sinceDate: date1)
let flag:NSCalendarUnit = [.Minute, .Second]
// 参数 options 不能为 0 ,0 不是一个有效的值。对于没有选项,使用 NSCalendarOptions(rawValue: 0)
let compt:NSDateComponents = NSCalendar.currentCalendar().components(flag,
fromDate: date1,
toDate: date2,
options: NSCalendarOptions(rawValue: 0))
7、NSDateComponents 与 NSDate 的相互转换
let calendar:NSCalendar = NSCalendar.currentCalendar()
// NSDate 转 NSDateComponents
let compt:NSDateComponents = calendar.components([.Year, .Month], fromDate: NSDate())
// NSDateComponents 转 NSDate
// 转换时间时,使用默认的时区 GMT 时区
var date:NSDate = calendar.dateFromComponents(compt)!
// 得到本地时间,避免时区问题
let timeInterval = NSTimeZone.systemTimeZone().secondsFromGMT
date = date.dateByAddingTimeInterval(NSTimeInterval(timeInterval))
8、NSDateComponents 与 NSDate 的计算
let compt:NSDateComponents = NSDateComponents()
compt.day = 25
compt.hour = 11
compt.minute = 12
// NSDate 加上 NSDateComponents 表示的一段时间
var date:NSDate = NSCalendar.currentCalendar().dateByAddingComponents(compt,
toDate: NSDate(),
options: NSCalendarOptions(rawValue: 0))!
date = date.dateByAddingTimeInterval(NSTimeInterval(NSTimeZone.systemTimeZone().secondsFromGMT))
9、NSDateFormatter 的时间格式化
- 使用 NSDateFormatter 转换时间字符串时,默认的时区是系统时区,例如在中国一般都是北京时间(+8),如果直接转换会导致结果相差8小时,所以一般的做法是先指定时区为GMT标准时间再转换。
/*
G -- 纪元 一般会显示公元前(BC)和公元(AD)
y -- 年 假如是2013年,那么 yyyy=2013,yy=13
M -- 月 假如是3月,那么 M=3,MM=03,MMM=Mar,MMMM=March;
假如是11月,那么M=11,MM=11,MMM=Nov,MMMM=November
w -- 一年中的第几周 假如是1月8日,那么 w=2(这一年的第二个周)
W -- 一个月中的第几周 与日历排列有关,假如是2013年4月21日,那么 W=4(这个月的第四个周)
F -- 月份包含的周 与日历排列无关,和上面的 W 不一样,F 只是单纯以7天为一个单位来统计周,
例如7号一定是第一个周,15号一定是第三个周,与日历排列无关。
D -- 一年中的第几天 假如是1月20日,那么 D=20(这一年的第20天);假如是2月25日,那么 D=31+25=56(这一年的第56天)
d -- 一个月中的第几天 假如是5号,那么 d=5,dd=05 假如是15号,那么 d=15,dd=15
E -- 星期几 假如是星期五,那么 E=Fri,EEEE=Friday
a -- 上午(AM)/下午(PM)
H -- 24小时制 显示为0--23,假如是午夜00:40,那么 H=0:40,HH=00:40
h -- 12小时制 显示为1--12,假如是午夜00:40,那么 h=12:40
K -- 12小时制 显示为0--11,假如是午夜00:40,那么 K=0:40,KK=00:40
k -- 24小时制 显示为1--24,假如是午夜00:40,那么 k=24:40
m -- 分钟 假如是5分钟,那么 m=5,mm=05;假如是45分钟,那么 m=45,mm=45
s -- 秒 假如是5秒钟,那么 s=5,ss=05;假如是45秒钟,那么 s=45,ss=45
S -- 毫秒 一般用 SSS 来显示
z -- 时区 表现形式为 GMT+08:00
Z -- 时区 表现形式为 +0800
*/
let formatter:NSDateFormatter = NSDateFormatter()
// 设置时区,不设置时默认的时区是系统时区(GMT+8)
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
// 设置日期格式,以字符串表示的日期形式的格式
formatter.dateFormat = "G yyyy-MM-dd E D F w W a z HH:mm:ss.SSS"
// 格式化日期,GMT 时间,NSDate 转 NSString
let str:String = formatter.stringFromDate(NSDate())
10、1437494603 (秒) 格式 转 YYYY-MM-dd HH:mm:ss 格式
// 计算日期
let date:NSDate = NSDate(timeIntervalSince1970: 1437494603)
// 创建时间戳
let formatter:NSDateFormatter = NSDateFormatter()
// 设置日期格式,以字符串表示的日期形式的格式
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
// 转换成指定的格式
let str:String = formatter.stringFromDate(date)
11、NSDate 与 NSString 的相互转换
let formatter:NSDateFormatter = NSDateFormatter()
// 设置时区,不设置时默认的时区是系统时区(GMT+8)
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
// 加入一些别的英文字符串时,需用单引号来引入
formatter.dateFormat = "yyyy年MM月dd日 HH点mm分ss秒 'iOS Date Test'"
// NSString 转 NSDate
let date:NSDate = formatter.dateFromString("2016年01月12日 1点8分50秒")!
// NSDate 转 NSString
let str:String = formatter.stringFromDate(date)
- 通过String类的toDate方法创建
let date = "2015-07-26".toDate(formatString: "YYYY-MM-DD")
- 通过NSDate的静态方法创建
- let todayDate = NSDate.today()
- let yesterdayDate = NSDate.yesterday()
- let tomorrowDate = NSDate.tomorrow()
获取日期中年月日等信息
我们可以通过NSDate的以下属性获取
- .year
- .month
- .weekOfMonth
- .weekday
- .weekdayOrdinal
- .day
- .hour
- .minute
- .second
- .era
- .firstDayOfWeek // (first day of the week of passed date)
- .lastDayOfWeek // (last day of the week of passed date)
- .nearestHour // (nearest hour of the passed date)
- .isLeapYear() // true if date's represented year is leap
- .monthDays() // return the number of days in date's represented month
修改日期
- var date = NSDate()
- date = date.set("hour",value: 12)!
- date = date.set("day",value: 1)!
日期运算
let date = NSDate()
let tomorrow = date+1.day
let two_months_ago = date-2.months
时区转换
- let date = NSDate() //本地时区
- let date_as_utc = date.toUTC() //UTC 时间
- let date_as_beijing = date_as_utc.toTimezone("UTC+8") //北京时间
日期比较
我们可以通过数学运算符比较
- let date1 = NSDate.date(fromString: "2015-07-26", format: DateFormat.Custom("YYYY-MM-DD"))
- let date2 = NSDate.date(fromString: "2015-07-27", format: DateFormat.Custom("YYYY-MM-DD"))
-
- if date2 > date1 {
-
- // TODO something
-
- }
还可以通过NSDate的以下一些方法来比较
let isInRange : Bool = date1.isInTimeRange("11:00","15:00")
- .isToday() // true if represented date is today
- .isTomorrow()
- .isYesterday()
- .isThisWeek() // true if represented date's week is the current week
- .isSameWeekOf(date: NSDate) // true if two dates share the same year's week
- .dateAtWeekStart() // return the date where current's date week starts
- .beginningOfDay() // return the same date of the sender with time set to 00:00:00
- .endOfDay() // return the same date of the sender with time set to 23:59:59
- .beginningOfMonth() // return the date which represent the first day of the sender date's month
- .endOfMonth() // return the date which represent the last day of the sender date's month
- .beginningOfYear() // return the date which represent the first day of the sender date's year
- .endOfYear() // return the date which represent the last day of the sender date's year
- .isWeekday() // true if current sender date is a week day
- .isWeekend() // true if current sender date is a weekend day (sat/sun)
NSDate转换为字符串
let string = date.toString(format: DateFormat.Custom("YYYY-MM-DD"))
也可以在转换方法中指定NSDateFormatterStyle
let string = date.toString(dateStyle: .ShortStyle timeStyle:.LongStyle relativeDate:true)
还可以通过以下方法转换为特定的字符串
- .toISOString() // DateFormat.ISO8601
- .toShortString() // short style, both time and date are printed
- .toMediumString() // medium style, both time and date are printed
- .toLongString() // full style, both time and date are printed
- .toShortDateString() // short style, print only date
- .toShortTimeString() // short style, print only time
- .toMediumDateString() // medium style, print only date
- .toMediumTimeString() // medium style, print only time
- .toLongDateString() // long style, print only date
- .toLongTimeString() // long style, print only time
最后我们还可以输出相对时间的格式,比如输出"2 hours ago"
- var d = NSDate()-2.hour
- var abb = d.toRelativeString(abbreviated: true, maxUnits: 3)
- println("data: \(abb)")
文章来源网络:点击这里查看源文.