概览
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
: aDateFormat
struct. To use custom strings pass.custom()
and pass the value of the formatter
例子
let date = DateInRegion()
let str = date.string(format: .custom("yyyy-MM-dd HH:mm:ss")) // example output: 2016-09-28 13:48:17
// you can also use the shortcut:
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
: aDateFormat
struct. To use custom strings pass .custom() and pass the value of the formatter
例子
let date = DateInRegion()
// Here some combinations of ISO8601DateTimeFormatter.Options you can set to format (or parse) an ISO8601 datetime
let iso8601_ex_1 = date.string(format: .iso8601(options: [.withInternetDateTime])) // 2016-09-29T10:47:39+02:00
let iso8601_ex_2 = date.string(format: .iso8601(options: [.withFullDate])) // 2016-09-29
let iso8601_ex_3 = date.string(format: .iso8601(options: [.withWeekOfYear,.withYear])) // 2016W40
let iso8601_ex_4 = date.string(format: .iso8601(options: [.withFullTime,.withFullDate,.withSpaceBetweenDateAndTime])) // 2016-09-29 10:49:42+02:00
let iso8601_ex_5 = date.string(format: .iso8601(options: [.withMonth,.withYear,.withTime])) // 20160910:50:36
获取 AltRss 格式的时间字符串
SwiftDate 也提供对 RSS
和AltRSS
时间格式的支持。(包括解析与生成字符串)
声明
func string(format: DateFormat) -> String // with DateFormat set to .rss(alt: Bool)
参数
format
: aDateFormat
struct. To getRSS/AltRSS
pass.rss(alt: Bool)
and passtrue
orfalse
to set the alt format.
例子
let date = DateInRegion()
let altrss_string = date.string(format: .rss(alt: true)) // Alt RSS Format: 29 Sep 2016 10:55:34 +0200
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
: aDateFormat
struct. To get.NET
pass.dotNET
and passtrue
orfalse
to set the alt format.
例子
let date = DateInRegion()
let donet_string = date.string(format: .dotNET) // /Date(1475139751633+0200)/
获取扩展化(EDTF)格式的时间字符串
SwiftDate 也提供对扩展化日期/时间格式的支持。
声明
func string(format: DateFormat) -> String // with DateFormat set to .extended
参数
format
: aDateFormat
struct. To get extended datetime formatted string pass.extended
and passtrue
orfalse
to set the alt format.
例子
let date = DateInRegion()
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
orcomponents
: specify the component or an array of compone.extended
and passtrue
orfalse
to set the alt format.
例子
let dateA = DateInRegion()
let dateB = dateA + 20.minutes + 120.seconds // create another date with some diff
// Get difference in minutes
let diff_in_minutes = (dateB - dateA).in(.minute) // 22 minutes
// Get difference in seconds and minutes
let diff_in_min_and_secs = (dateB - dateA).in([.minute,.second]) // lower components are grouped. You will get .second=0, .minute=2
// This is another example
let another_diff: TimeInterval = 125 // 125 seconds
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 asDateFormatter.Style
. If not specified.medium
is used.timeStyle
: the style used to print a time asDateFormatter.Style
. If not specified.medium
is used.
例子
let date = DateInRegion() // create a date from current time in local device's region and calendar
// Some examples of date as string formatted with different styles for date and time
let example_1 = date.string(dateStyle: .medium, timeStyle: .long) // Sep 29, 2015, 1:01:13 PM GMT+2
let example_2 = date.string(dateStyle: .short, timeStyle: .short) // 9/29/15, 1:00 PM
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
例子
// Returned tuples (in EN):
// "past month" for interval, "Aug, 29 2016" for relevant time
let dateA = DateInRegion() - 1.months
let (colloquial,relevantTime) = try! dateA.colloquialSinceNow()
// Returned tuples (in EN):
// "2 hours ago" for interval, "at 11:28" for relevant time
let dateB = DateInRegion() - 2.hours - 14.minutes
let (colloquial,relevantTime) = try! dateB.colloquialSinceNow()
// Returned tuples (in EN):
// // "14 minutes ago" for interval, nil for relevant time
let dateC = DateInRegion() - 14.minutes
let (colloquial,relevantTime) = try! dateC.colloquialSinceNow()
// Returned tuples (in EN):
// "2012" for interval, "Sep 2012" for relevant time
let dateD = DateInRegion() - 4.years
let (colloquial,relevantTime) = try! dateD.colloquialSinceNow()
指定单位下,获取两个时间之间的间隔字符串
SwiftDate 可以在指定组件单位的前提下,获取两个时间的差值,并输出为字符串;你可以设置任意一个组件的显示位置,比如(年使用 y
或years
来表述);组件所对应的最大值以及最小值都会被妥善处理,比如日月年这些单位最小值是 1,最大值是 12,而时分秒的最大值是 60 ,最小值是 0。
声明
获取一个时间与现在时刻的差值时
func timeComponentsSinceNow(options:,shared:) throws -> String
获取两个时间之间的差值时
func timeComponents(to:options:shared:) throws -> String
异常
如果不能计算出有效的时间间隔,将会抛出 .FailedToCalculate
错误。
参数
to
: reference date for comparisoroptions
: struct ComponentsFormatterOptions which defines a list of options used to print time components
例子
let region = Region.GMT()
let dateB = DateInRegion(absoluteDate: Date(), in: region)
let dateC = dateB - 2.years - 4.months - 5.days
let str2 = try! dateC.timeComponents(toDate: dateB, options: ComponentsFormatterOptions(style: .positional)) // -2y 4m 0w 5d 0:00:00
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
let str4 = try! dateC.timeComponents(toDate: dateB, options: ComponentsFormatterOptions(zero: .dropAll)) // -2y 4m 5d
let dateD = dateB + 1.months
let str5 = try! dateD.timeComponentsSinceNow(options: ComponentsFormatterOptions(allowedUnits: [.weekOfMonth,.day], zero: .dropAll)) // 4w 2d