Date Formatting
Overview
SwiftDate exposes several convenient functions to print (and parse, of course) dates and time intervals as strings:
- as custom string defined by tr35-31 format; for example
"yyyy-MM-dd"
for"2015-01-05"
- as ISO8601 strings with all available sub specs
- as .NET datetime format
- as AltRSS and RSS datetime format
- as extended string with date and time
- time intervals in other time units; for example
(date2 - date1).in(.hours)
- human readable / colloquial strings; for example
"1 hour ago", "1m", "now"
etc. (with locale support) - time components between two dates; for example the differences between two dates as
"2h,5m,3s"
Date to Custom Format
You can convert an instance of DateInRegion
or Date
to a string with a custom specified string as format using .string()
function. A table of the available format specifiers is available in this Unicode standard spec and it's the same commonly used in Cocoa.
Declaration
Using .dateFormat:
// with DateFormat set to .custom([format string])
func string(format: DateFormat) -> String
Using shortcut function:
// shortcut to pass directly the format of the string
func string(custom: String) -> String
Parameters
format
: aDateFormat
struct. To use custom strings pass.custom()
and pass the value of the formatter
Example
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 |
Date to ISO8601 Format
SwiftDate supports a full featured ISO8601 DateTime formatter. It allows you to specify your custom configuration for any variant of the specs. You can use
Declaration
// with DateFormat set to .custom()
func string(format: DateFormat) -> String
Parameters
format
: aDateFormat
struct. To use custom strings pass.custom()
and pass the value of the formatter
Example
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 |
Date to AltRSS Format
SwiftDate also supports RSS and AltRSS Date Time format (both for parse and as formatter).
Declaration
func string(format: DateFormat) -> String // with DateFormat set to .rss(alt: Bool)
Parameters
format
: aDateFormat
struct. To get RSS/AltRSS pass.rss(alt: Bool)
and pass true or false to set the alt format.
Example
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 |
Date to .NET Format
SwiftDate also supports .NET Date Time format (both for parse and as formatter).
Declaration
func string(format: DateFormat) -> String // with DateFormat set to .dotNET
Parameters
format
: aDateFormat
struct. To get .NET formatted string pass.dotNET
and pass true or false to set the alt format.
Example
let date = DateInRegion() | |
let donet_string = date.string(format: .dotNET) // /Date(1475139751633+0200)/ |
Date to Extended Format
SwiftDate support extended date time format.
Declaration
func string(format: DateFormat) -> String // with DateFormat set to .extended
Parameters
format
: aDateFormat
struct. To get extended datetime formatted string pass.extended
and pass true or false to set the alt format.
Example
let date = DateInRegion() | |
let str = date.string(format: .extended) // Thu 29-Sep-2016 AD 11:31:23.886 GMT+2 |
Time Interval to string
It's pretty easy to convert an absolute time interval or a difference between two dates and express it as string in various time components. When possible lower time components are grouped at upper level (so, for example if you want to get .minutes and .seconds of 120secs you will get 0 seconds and 2 minutes.
However with an interval of 125 seconds you will get 2 minutes and 5 seconds.
Declaration
Multiple time components
public func `in`(_ components: [Calendar.Component], of calendar: CalendarName? = nil) -> [Calendar.Component : Int]
Single time components
public func `in`(_ component: Calendar.Component, of calendar: CalendarName? = nil) -> Int?
Parameters
component
orcomponents
: specify the component or an array of compone.extended
and pass true or false to set the alt format.
Example
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 |
Date & Time with Style
You can user standard's Foundation date formatting which allows you to specify a style for date and time.
Declaration
func string(dateStyle: DateFormatter.Style = .medium, timeStyle: DateFormatter.Style = .medium) -> String
Parameters
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.
Example
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 |
Human Readable/Colloquial String
You can user standard's Foundation date formatting which allows you to specify a style for date and time.
Colloquial string represent an human readable format used to express time intervals like difference between dates.
Declaration
Difference between a date and now
func colloquialSinceNow() throws -> (date: String, time: String?)
Difference between two dates
func colloquial(toDate date: DateInRegion) throws -> (date: String, time: String?)
Exception
Raise an exception .DifferentCalendar
if both date are in different calendars.
Raise an exception .FailedToCalculate
if time interval cannot be evaluated
Parameters
date
: reference date for comparisor
Example
// 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() |
Time Components
Using SwiftDate you can get the difference between two dates and express it as a string of time components.
You can configure the style in which each components will be displayed (ex. "y" or "years"), the number of max components will be displayed and how the formatter should treat zero values.
Declaration
Time components between a date and now
func timeComponentsSinceNow(options:,shared:) throws -> String
Time components between two dates
func timeComponents(to:options:shared:) throws -> String
Exception
Raise an exception .FailedToCalculate
if time interval cannot be evaluated
Parameters
to
: reference date for comparisoroptions
: structComponentsFormatterOptions
which defines a list of options used to print time components
Example
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 |