当前位置:首页 » IOS文章 » Swift之NSData的使用

Swift之NSData的使用

作者:KNN   日期:2020-03-05   分类:IOS文章

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文件中,添加如下内容:

  1. source 'https://github.com/CocoaPods/Specs.git'
  2. platform :ios, '8.0'
  3. use_frameworks!
  4. pod 'SwiftDate'

最后,执行如下命令安装

$ pod install

创建日期

  • 通过解析字符串创建

let date_custom = NSDate.date(fromString: "2015-07-26", format: DateFormat.Custom("YYYY-MM-DD"))

1、NSDate 的创建

  1. // 当前时间值,GMT 时间
  2. let date1:NSDate = NSDate()
  3. // 当前时间加 n 秒后的值
  4. let date2:NSDate = NSDate(timeIntervalSinceNow: 10)
  5. // 某个时间增加 n 秒后的值
  6. let date3:NSDate = NSDate(timeInterval: 10, sinceDate: date2)
  7. // 从 1970-01-01 00:00:00 (GMT) 增加 n 秒后的值
  8. let date4:NSDate = NSDate(timeIntervalSince1970: 3600)
  9. // 从 2001-01-01 00:00:00 (GMT) 增加 n 秒后的值
  10. let date5:NSDate = NSDate(timeIntervalSinceReferenceDate: 10)
  11. // 未来某一个随机时间
  12. let date6:NSDate = NSDate.distantFuture()
  13. // 过去某一个随机时间
  14. let date7:NSDate = NSDate.distantPast()
  15. // 某个时间增加 n 秒后的值
  16. 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 时间间隔的计算

  1. let date1 = NSDate()
  2. let date2 = date1.dateByAddingTimeInterval(20)
  3. // 实例保存的时间 与 当前时间 的时间间隔,单位 秒
  4. let interval1:NSTimeInterval = date2.timeIntervalSinceNow
  5. // 实例保存的时间 与 指定时间 的时间间隔,单位 秒
  6. let interval2:NSTimeInterval = date2.timeIntervalSinceDate(date1)
  7. // 实例保存的时间 与 1970-01-01 00:00:00 (GMT) 的时间间隔,单位 秒
  8. let interval3:NSTimeInterval = date1.timeIntervalSince1970
  9. // 实例保存的时间 与 2001-01-01 00:00:00 (GMT) 的时间间隔,单位 秒
  10. let interval4:NSTimeInterval = date1.timeIntervalSinceReferenceDate
  11. // 当前时间 与 2001-01-01 00:00:00 (GMT) 的时间间隔,单位 秒
  12. let interval5:NSTimeInterval = NSDate.timeIntervalSinceReferenceDate()

3、NSDate 时间的比较

  1. let date1 = NSDate()
  2. let date2 = date1.dateByAddingTimeInterval(20)
  3. // 判断两个时间是否相等
  4. let bl:Bool = date1.isEqualToDate(date2)
  5. // 比较两个时间大小
  6. let result:NSComparisonResult = date1.compare(date2)
  7. // 比较两个时间,返回 较早的时间
  8. let date3 = date1.earlierDate(date2)
  9. // 比较两个时间,返回 较晚的时间
  10. let date4 = date1.laterDate(date2)

4、时区差值转换

  1. // 得到当前时间(世界标准时间 UTC/GMT)
  2. var date:NSDate = NSDate()
  3. // 设置系统时区为本地时区
  4. let zone:NSTimeZone = NSTimeZone.systemTimeZone()
  5. // 计算本地时区与 GMT 时区的时间差
  6. let second:Int = zone.secondsFromGMT
  7. // 在 GMT 时间基础上追加时间差值,得到本地时间
  8. date = date.dateByAddingTimeInterval(NSTimeInterval(second))

5、NSDateComponents 的创建

  1. // 由手动设置创建
  2. let compt1:NSDateComponents = NSDateComponents()
  3. // 日历
  4. compt1.calendar = NSCalendar.currentCalendar()
  5. // 时区
  6. compt1.timeZone = NSTimeZone.systemTimeZone()
  7. compt1.era = 1 // 纪元
  8. compt1.year = 2016 // 年
  9. compt1.month = 3 // 月
  10. compt1.day = 1 // 日
  11. compt1.hour = 10 // 时
  12. compt1.minute = 12 // 分
  13. compt1.second = 55 // 秒
  14. compt1.nanosecond = 280 // 微妙
  15. compt1.quarter = 0 // 刻钟
  16. compt1.weekday = 3 // 周几
  17. compt1.weekdayOrdinal = 1 // 指定日期为本月的第几个星期几
  18. compt1.weekOfMonth = 1 // 指定日期为本月的第几周
  19. compt1.weekOfYear = 10 // 指定日期为本年的第几周
  20. compt1.yearForWeekOfYear = 2016 //
  21. // 由已知 date 创建
  22. /*
  23. 只有明确指定了 unitFlags,NSDateComponents 相应的那一部分才有值。在 Swift 2.2 中不能使用 “|” 连接两个 Unit 枚举值
  24. */
  25. let flag:NSCalendarUnit = [.Era, .Year, .Month, .Day, .Hour, .Minute, .Second, .Nanosecond, .Quarter, .Weekday,
  26. .WeekdayOrdinal, .WeekOfMonth, .WeekOfYear, .WeekOfYear, .Calendar, .TimeZone]
  27. let compt2:NSDateComponents = NSCalendar.currentCalendar().components(flag, fromDate: NSDate())

6、NSDateComponents 时间间隔的计算

  1. let date1:NSDate = NSDate()
  2. let date2:NSDate = NSDate(timeInterval: 5*60*60+75, sinceDate: date1)
  3. let flag:NSCalendarUnit = [.Minute, .Second]
  4. // 参数 options 不能为 0 ,0 不是一个有效的值。对于没有选项,使用 NSCalendarOptions(rawValue: 0)
  5. let compt:NSDateComponents = NSCalendar.currentCalendar().components(flag,
  6. fromDate: date1,
  7. toDate: date2,
  8. options: NSCalendarOptions(rawValue: 0))

7、NSDateComponents 与 NSDate 的相互转换

  1. let calendar:NSCalendar = NSCalendar.currentCalendar()
  2. // NSDate 转 NSDateComponents
  3. let compt:NSDateComponents = calendar.components([.Year, .Month], fromDate: NSDate())
  4. // NSDateComponents 转 NSDate
  5. // 转换时间时,使用默认的时区 GMT 时区
  6. var date:NSDate = calendar.dateFromComponents(compt)!
  7. // 得到本地时间,避免时区问题
  8. let timeInterval = NSTimeZone.systemTimeZone().secondsFromGMT
  9. date = date.dateByAddingTimeInterval(NSTimeInterval(timeInterval))

8、NSDateComponents 与 NSDate 的计算

  1. let compt:NSDateComponents = NSDateComponents()
  2. compt.day = 25
  3. compt.hour = 11
  4. compt.minute = 12
  5. // NSDate 加上 NSDateComponents 表示的一段时间
  6. var date:NSDate = NSCalendar.currentCalendar().dateByAddingComponents(compt,
  7. toDate: NSDate(),
  8. options: NSCalendarOptions(rawValue: 0))!
  9. date = date.dateByAddingTimeInterval(NSTimeInterval(NSTimeZone.systemTimeZone().secondsFromGMT))

9、NSDateFormatter 的时间格式化

  • 使用 NSDateFormatter 转换时间字符串时,默认的时区是系统时区,例如在中国一般都是北京时间(+8),如果直接转换会导致结果相差8小时,所以一般的做法是先指定时区为GMT标准时间再转换。
  1. /*
  2. G -- 纪元 一般会显示公元前(BC)和公元(AD)
  3. y -- 年 假如是2013年,那么 yyyy=2013,yy=13
  4. M -- 月 假如是3月,那么 M=3,MM=03,MMM=Mar,MMMM=March;
  5. 假如是11月,那么M=11,MM=11,MMM=Nov,MMMM=November
  6. w -- 一年中的第几周 假如是1月8日,那么 w=2(这一年的第二个周)
  7. W -- 一个月中的第几周 与日历排列有关,假如是2013年4月21日,那么 W=4(这个月的第四个周)
  8. F -- 月份包含的周 与日历排列无关,和上面的 W 不一样,F 只是单纯以7天为一个单位来统计周,
  9. 例如7号一定是第一个周,15号一定是第三个周,与日历排列无关。
  10. D -- 一年中的第几天 假如是1月20日,那么 D=20(这一年的第20天);假如是2月25日,那么 D=31+25=56(这一年的第56天)
  11. d -- 一个月中的第几天 假如是5号,那么 d=5,dd=05 假如是15号,那么 d=15,dd=15
  12. E -- 星期几 假如是星期五,那么 E=Fri,EEEE=Friday
  13. a -- 上午(AM)/下午(PM)
  14. H -- 24小时制 显示为0--23,假如是午夜00:40,那么 H=0:40,HH=00:40
  15. h -- 12小时制 显示为1--12,假如是午夜00:40,那么 h=12:40
  16. K -- 12小时制 显示为0--11,假如是午夜00:40,那么 K=0:40,KK=00:40
  17. k -- 24小时制 显示为1--24,假如是午夜00:40,那么 k=24:40
  18. m -- 分钟 假如是5分钟,那么 m=5,mm=05;假如是45分钟,那么 m=45,mm=45
  19. s -- 秒 假如是5秒钟,那么 s=5,ss=05;假如是45秒钟,那么 s=45,ss=45
  20. S -- 毫秒 一般用 SSS 来显示
  21. z -- 时区 表现形式为 GMT+08:00
  22. Z -- 时区 表现形式为 +0800
  23. */
  24. let formatter:NSDateFormatter = NSDateFormatter()
  25. // 设置时区,不设置时默认的时区是系统时区(GMT+8)
  26. formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
  27. // 设置日期格式,以字符串表示的日期形式的格式
  28. formatter.dateFormat = "G yyyy-MM-dd E D F w W a z HH:mm:ss.SSS"
  29. // 格式化日期,GMT 时间,NSDate 转 NSString
  30. let str:String = formatter.stringFromDate(NSDate())

10、1437494603 (秒) 格式 转 YYYY-MM-dd HH:mm:ss 格式

  1. // 计算日期
  2. let date:NSDate = NSDate(timeIntervalSince1970: 1437494603)
  3. // 创建时间戳
  4. let formatter:NSDateFormatter = NSDateFormatter()
  5. // 设置日期格式,以字符串表示的日期形式的格式
  6. formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
  7. // 转换成指定的格式
  8. let str:String = formatter.stringFromDate(date)

11、NSDate 与 NSString 的相互转换

  1. let formatter:NSDateFormatter = NSDateFormatter()
  2. // 设置时区,不设置时默认的时区是系统时区(GMT+8)
  3. formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
  4. // 加入一些别的英文字符串时,需用单引号来引入
  5. formatter.dateFormat = "yyyy年MM月dd日 HH点mm分ss秒 'iOS Date Test'"
  6. // NSString 转 NSDate
  7. let date:NSDate = formatter.dateFromString("2016年01月12日 1点8分50秒")!
  8. // NSDate 转 NSString
  9. let str:String = formatter.stringFromDate(date)


  • 通过String类的toDate方法创建
let date = "2015-07-26".toDate(formatString: "YYYY-MM-DD")
  • 通过NSDate的静态方法创建
  1. let todayDate = NSDate.today()
  2. let yesterdayDate = NSDate.yesterday()
  3. let tomorrowDate = NSDate.tomorrow()

获取日期中年月日等信息

我们可以通过NSDate的以下属性获取

  1. .year
  2. .month
  3. .weekOfMonth
  4. .weekday
  5. .weekdayOrdinal
  6. .day
  7. .hour
  8. .minute
  9. .second
  10. .era
  11. .firstDayOfWeek // (first day of the week of passed date)
  12. .lastDayOfWeek // (last day of the week of passed date)
  13. .nearestHour // (nearest hour of the passed date)
  14. .isLeapYear() // true if date's represented year is leap
  15. .monthDays() // return the number of days in date's represented month

修改日期

  1. var date = NSDate()
  2. date = date.set("hour",value: 12)!
  3. date = date.set("day",value: 1)!

日期运算

  1. let date = NSDate()
  2. let tomorrow = date+1.day
  3. let two_months_ago = date-2.months

时区转换

  1. let date = NSDate() //本地时区
  2. let date_as_utc = date.toUTC() //UTC 时间
  3. let date_as_beijing = date_as_utc.toTimezone("UTC+8") //北京时间

日期比较

我们可以通过数学运算符比较

  1. let date1 = NSDate.date(fromString: "2015-07-26", format: DateFormat.Custom("YYYY-MM-DD"))
  2. let date2 = NSDate.date(fromString: "2015-07-27", format: DateFormat.Custom("YYYY-MM-DD"))
  3. if date2 > date1 {
  4. // TODO something
  5. }

还可以通过NSDate的以下一些方法来比较

let isInRange : Bool = date1.isInTimeRange("11:00","15:00")
  1. .isToday() // true if represented date is today
  2. .isTomorrow()
  3. .isYesterday()
  4. .isThisWeek() // true if represented date's week is the current week
  5. .isSameWeekOf(date: NSDate) // true if two dates share the same year's week
  6. .dateAtWeekStart() // return the date where current's date week starts
  7. .beginningOfDay() // return the same date of the sender with time set to 00:00:00
  8. .endOfDay() // return the same date of the sender with time set to 23:59:59
  9. .beginningOfMonth() // return the date which represent the first day of the sender date's month
  10. .endOfMonth() // return the date which represent the last day of the sender date's month
  11. .beginningOfYear() // return the date which represent the first day of the sender date's year
  12. .endOfYear() // return the date which represent the last day of the sender date's year
  13. .isWeekday() // true if current sender date is a week day
  14. .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)

还可以通过以下方法转换为特定的字符串

  1. .toISOString() // DateFormat.ISO8601
  2. .toShortString() // short style, both time and date are printed
  3. .toMediumString() // medium style, both time and date are printed
  4. .toLongString() // full style, both time and date are printed
  5. .toShortDateString() // short style, print only date
  6. .toShortTimeString() // short style, print only time
  7. .toMediumDateString() // medium style, print only date
  8. .toMediumTimeString() // medium style, print only time
  9. .toLongDateString() // long style, print only date
  10. .toLongTimeString() // long style, print only time

最后我们还可以输出相对时间的格式,比如输出"2 hours ago"

  1. var d = NSDate()-2.hour
  2. var abb = d.toRelativeString(abbreviated: true, maxUnits: 3)
  3. println("data: \(abb)")


 

 

 

 

文章来源网络:点击这里查看源文.