概览

SwiftDate 提供多个简便的方法来输出或解析时间和时间间隔字符串,以下为常见时间格式举例:

  • 使用 tr35-31格式的时间格式字符串,例如 yyyy-MM-dd 对应 2015-01-05
  • 任意符合 ISO8601 及其子规范的时间格式字符串
  • 符合 .NET 的时间格式字符串
  • 扩展化日期/时间格式,详情请参照 EDTF
  • 声明单位的时间差,如 (date2 - date1).in(.hours)
  • 人类可读或口语化的字符串,如 "1 hour ago", "1m", "now"
  • 两个时间之间的差值,比如 "2h,5m,3s"

获取自定义格式的时间字符串


你可以使用 .string()方法传入自定义格式,获得时间实例生成对应的字符串。字符串的 Unicode 规范与 Cocoa 用法一致。

声明 DateFormat 包含了 .custom自定义格式,你可以使用通用的 // with DateFormat set to .custom([format string]) func string(format: DateFormat) -> String

也可以直接使用接受自定义格式的方法 // shortcut to pass directly the format of the string func string(custom: String) -> String

参数

  • format: a DateFormat struct. To use custom strings pass .custom() and pass the value of the formatter

例子

  1. let date = DateInRegion()
  2. let str = date.string(format: .custom("yyyy-MM-dd HH:mm:ss")) // example output: 2016-09-28 13:48:17
  3. // you can also use the shortcut:
  4. let str = date.string(custom: "yyyy-MM-dd HH:mm:ss") // same result


获取 ISO8601 格式的时间字符串

SwiftDate 支持 ISO8601 时间规范的所有要求。你可以基于其子规范而自定义格式。

声明 // with DateFormat set to .custom() func string(format: DateFormat) -> String

参数

  • format: a DateFormat struct. To use custom strings pass .custom() and pass the value of the formatter

例子

  1. let date = DateInRegion()
  2. // Here some combinations of ISO8601DateTimeFormatter.Options you can set to format (or parse) an ISO8601 datetime
  3. let iso8601_ex_1 = date.string(format: .iso8601(options: [.withInternetDateTime])) // 2016-09-29T10:47:39+02:00
  4. let iso8601_ex_2 = date.string(format: .iso8601(options: [.withFullDate])) // 2016-09-29
  5. let iso8601_ex_3 = date.string(format: .iso8601(options: [.withWeekOfYear,.withYear])) // 2016W40
  6. let iso8601_ex_4 = date.string(format: .iso8601(options: [.withFullTime,.withFullDate,.withSpaceBetweenDateAndTime])) // 2016-09-29 10:49:42+02:00
  7. let iso8601_ex_5 = date.string(format: .iso8601(options: [.withMonth,.withYear,.withTime])) // 20160910:50:36


获取 AltRss 格式的时间字符串

SwiftDate 也提供对 RSSAltRSS 时间格式的支持。(包括解析与生成字符串)

声明 func string(format: DateFormat) -> String // with DateFormat set to .rss(alt: Bool)

参数

  • format: a DateFormat struct. To get RSS/AltRSS pass.rss(alt: Bool) and pass true or false to set the alt format.

例子

  1. let date = DateInRegion()
  2. let altrss_string = date.string(format: .rss(alt: true)) // Alt RSS Format: 29 Sep 2016 10:55:34 +0200
  3. let rss_string = date.string(format: .rss(alt: false)) // RSS Format: Thu, 29 Sep 2016 10:55:34 +0200


获取 .NET 格式的时间字符串

SwiftDate 也提供对 .NET 时间格式的支持。(包括解析与生成字符串)

声明 func string(format: DateFormat) -> String // with DateFormat set to .dotNET

参数

  • format: a DateFormat struct. To get .NET pass.dotNET and pass true or false to set the alt format.

例子

  1. let date = DateInRegion()
  2. let donet_string = date.string(format: .dotNET) // /Date(1475139751633+0200)/


获取扩展化(EDTF)格式的时间字符串

SwiftDate 也提供对扩展化日期/时间格式的支持。

声明 func string(format: DateFormat) -> String // with DateFormat set to .extended

参数

  • format: a DateFormat struct. To get extended datetime formatted string pass .extended and pass true or false to set the alt format.

例子

  1. let date = DateInRegion()
  2. let str = date.string(format: .extended) // Thu 29-Sep-2016 AD 11:31:23.886 GMT+2


获取时间间隔的字符串表述

借助 SwiftDate ,你可以很方便的将时间间隔或两个时间之间的差值,以一个或多个单位输出成字符串。如果你想要获取的低级单位的值可以被完整进位,那低级单位所对应的值就被赋值为 0。比如 120秒 如果转换成 的组合,会被转换成 2分 0秒; 125秒 则会得到 2分 5秒

声明 多个时间单位时 public func `in`(_ components: [Calendar.Component], of calendar: CalendarName? = nil) -> [Calendar.Component : Int] 单个时间单位时 public func `in`(_ component: Calendar.Component, of calendar: CalendarName? = nil) -> Int?

参数

  • component or components: specify the component or an array of compone .extended and pass true or false to set the alt format.

例子

  1. let dateA = DateInRegion()
  2. let dateB = dateA + 20.minutes + 120.seconds // create another date with some diff
  3. // Get difference in minutes
  4. let diff_in_minutes = (dateB - dateA).in(.minute) // 22 minutes
  5. // Get difference in seconds and minutes
  6. let diff_in_min_and_secs = (dateB - dateA).in([.minute,.second]) // lower components are grouped. You will get .second=0, .minute=2
  7. // This is another example
  8. let another_diff: TimeInterval = 125 // 125 seconds
  9. let diff_in_min_and_secs_2 = another_diff.in([.minute,.second]) // you will get .minute=2 and .second=5


获取 iOS 样式的时间字符串

你可以使用 Foundation 中的时间格式来输出时间字符串。

声明 func string(dateStyle: DateFormatter.Style = .medium, timeStyle: DateFormatter.Style = .medium) -> String

参数

  • dateStyle: the style used to print a date as DateFormatter.Style. If not specified.medium is used.
  • timeStyle: the style used to print a time as DateFormatter.Style. If not specified .medium is used.

例子

  1. let date = DateInRegion() // create a date from current time in local device's region and calendar
  2. // Some examples of date as string formatted with different styles for date and time
  3. let example_1 = date.string(dateStyle: .medium, timeStyle: .long) // Sep 29, 2015, 1:01:13 PM GMT+2
  4. let example_2 = date.string(dateStyle: .short, timeStyle: .short) // 9/29/15, 1:00 PM
  5. let example_3 = date.string(dateStyle: .long, timeStyle: .none) // September 29, 2015


获取人类可读或白话式时间字符串

你可以使用 Foundation 来自定义日期 - 时间格式来输出时间字符串;同样的,时间间隔也可以使用口语化字符串来表述。

声明 获取一个时间与现在时刻的差值时 func colloquialSinceNow() throws -> (date: String, time: String?) 获取两个时间之间的差值时 func colloquial(toDate date: DateInRegion) throws -> (date: String, time: String?) 注意:该方法返回的是一个日期与时间的元组。

异常 如果两个时间采用不同的日历,会抛出 .DifferentCalendar 异常; 如果无法计算出两个时间的间隔,会抛出 .FailedToCalculate 异常。

参数

  • date: reference date for comparisor

例子

  1. // Returned tuples (in EN):
  2. // "past month" for interval, "Aug, 29 2016" for relevant time
  3. let dateA = DateInRegion() - 1.months
  4. let (colloquial,relevantTime) = try! dateA.colloquialSinceNow()
  5. // Returned tuples (in EN):
  6. // "2 hours ago" for interval, "at 11:28" for relevant time
  7. let dateB = DateInRegion() - 2.hours - 14.minutes
  8. let (colloquial,relevantTime) = try! dateB.colloquialSinceNow()
  9. // Returned tuples (in EN):
  10. // // "14 minutes ago" for interval, nil for relevant time
  11. let dateC = DateInRegion() - 14.minutes
  12. let (colloquial,relevantTime) = try! dateC.colloquialSinceNow()
  13. // Returned tuples (in EN):
  14. // "2012" for interval, "Sep 2012" for relevant time
  15. let dateD = DateInRegion() - 4.years
  16. let (colloquial,relevantTime) = try! dateD.colloquialSinceNow()


指定单位下,获取两个时间之间的间隔字符串

SwiftDate 可以在指定组件单位的前提下,获取两个时间的差值,并输出为字符串;你可以设置任意一个组件的显示位置,比如(年使用 yyears来表述);组件所对应的最大值以及最小值都会被妥善处理,比如日月年这些单位最小值是 1,最大值是 12,而时分秒的最大值是 60 ,最小值是 0。

声明 获取一个时间与现在时刻的差值时 func timeComponentsSinceNow(options:,shared:) throws -> String 获取两个时间之间的差值时 func timeComponents(to:options:shared:) throws -> String

异常 如果不能计算出有效的时间间隔,将会抛出 .FailedToCalculate 错误。

参数

  • to : reference date for comparisor
  • options : struct ComponentsFormatterOptions which defines a list of options used to print time components

例子

  1. let region = Region.GMT()
  2. let dateB = DateInRegion(absoluteDate: Date(), in: region)
  3. let dateC = dateB - 2.years - 4.months - 5.days
  4. let str2 = try! dateC.timeComponents(toDate: dateB, options: ComponentsFormatterOptions(style: .positional)) // -2y 4m 0w 5d 0:00:00
  5. let str3 = try! dateC.timeComponents(toDate: dateB, options: ComponentsFormatterOptions(style: .full)) // -2 years, 4 months, 0 weeks, 5 days, 0 hours, 0 minutes, 0 seconds
  6. let str4 = try! dateC.timeComponents(toDate: dateB, options: ComponentsFormatterOptions(zero: .dropAll)) // -2y 4m 5d
  7. let dateD = dateB + 1.months
  8. let str5 = try! dateD.timeComponentsSinceNow(options: ComponentsFormatterOptions(allowedUnits: [.weekOfMonth,.day], zero: .dropAll)) // 4w 2d