Skip to content

Latest commit

 

History

History
190 lines (128 loc) · 8.77 KB

5.Date_Formatting.md

File metadata and controls

190 lines (128 loc) · 8.77 KB

Date Formatting

Formatting dates and transforms to string representation is really easy with SwiftDate. All the major formats are supported and are really easy to configure.

If you need to format a Date or DateInRegion in a String using a custom format you need to use toFormat(_:locale:) function.

func toFormat(_ format: String, locale: LocaleConvertible?) -> String

it takes two arguments:

  • format | String: the format of the string. It's defined by the Unicode DateTime format specs you can found here.
  • locale | LocaleConvertible?: Set a non nil value to force the formatter to use a different locale than the one assigned to the date itself (from date's region.locale property). Leave it nil to use the one assigned by the region itself (or, for plain Date instances the one set as SwiftDate.defaultRegion).

Example:

let rome = Region(calendar: Calendars.gregorian, zone: Zones.europeRome, locale: Locales.italian)
let date = DateInRegion(year: 2015, month: 1, day: 15, hour: 20, minute: 00, second: 5, nanosecond: 0, region: rome)

// Even if date's locale is set to `italian` we can still
// print in a different language by passing a non nil locale
// to the function.
let formattedString = date.toFormat("MMM dd yyyy", locale: Locales.english) // "Jan 15 2015"

^ Top

SwiftDate allows you to print date instances using a configurable ISO8601 formatter which is also compatible with older versions of iOS where Apple's own class is not available.

To use the ISO formatter call .toISO() function

func toISO(_ options: ISOFormatter.Options?) -> String

takes one optional argument:

  • options | ISOFormatter.Options: allows to customize the format of the output string by defining which kind of date must be into the final string (if you omit it withInternetDateTime is used).

ISOFormatter.Options defines an OptionSet with the following values:

  • withYear: The date representation includes the year. The format for year is inferred based on the other specified options. If withWeekOfYear is specified, YYYY is used. Otherwise, yyyy is used.
  • withMonth: The date representation includes the month. The format for month is MM.
  • withWeekOfYear: The date representation includes the week of the year. The format for week of year is ww, including the W prefix.
  • withDay: The date representation includes the day. The format for day is inferred based on provided options: If withMonth is specified, dd is used. If withWeekOfYear is specified, ee is used. Otherwise, DDD is used.
  • withTime: The date representation includes the time. The format for time is HH:mm:ss.
  • withTimeZone: The date representation includes the timezone. The format for timezone is ZZZZZ.
  • withSpaceBetweenDateAndTime: The date representation uses a space ( ) instead of T between the date and time.
  • withDashSeparatorInDate: The date representation uses the dash separator (-) in the date.
  • withFullDate: The date representation uses the colon separator (:) in the time.
  • withFullTime: The date representation includes the hour, minute, and second.
  • withInternetDateTime: The format used for internet date times, according to the RFC 3339 standard. Equivalent to specifying withFullDate, withFullTime, withDashSeparatorInDate, withColonSeparatorInTime, and withColonSeparatorInTimeZone.
  • withInternetDateTimeExtended: The format used for internet date times; it's similar to .withInternetDateTime but include milliseconds (yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ).
  • withoutTZSeparators: Print timezone of the date without time separator (+0200 instead of +02:00). You can combine it with the following other options: withInternetDateTimeExtended, withInternetDateTime and when withTimeZone == false && withTimeZone == true

Examples:

let regionRome = Region(calendar: Calendars.gregorian, zone: Zones.europeRome, locale: Locales.italian)
let date = DateInRegion("2017-07-22 00:00:00", format: "yyyy-MM-dd HH:mm:ss", region: regionRome)!

// ISO Formatting
let _ = date.toISO() // "2017-07-22T00:00:00+02:00"
let _ = date.toISO([.withFullDate]) // "2017-07-22"
let _ = date.toISO([.withFullDate, .withFullTime, .withDashSeparatorInDate, .withSpaceBetweenDateAndTime]) // "2017-07-22 00:00:00+02:00"

^ Top

CSOM DateTime (aka .NET DateTime) is a format defined by Microsoft as the number of 100-nanosecond intervals that have elapsed since 12:00 A.M., January 1, 0001 (learn more on MSDN documentation page).

Use the .toDotNET() function to create a string from a date instance.

func toDotNET() -> String

let date = "2017-06-20T14:49:19+02:00".toISODate()!
let dotNetString = date.toDotNET() // "/Date(1497962959000+0200)/"

^ Top

RSS and AltRSS formatted string can be generated from an instance of Date or DateInRegion using the .toRSS() function.

func toRSS(alt: Bool) -> String

takes only one argument:

  • alt | Bool: true to print the AltRSS variant, false to print the default RSS formatted string.

Examples:

let date = ... // 2017-06-20T14:49:19+02:00
let rssString = date.toRSS(alt: false) // "Tue, 20 Jun 2017 14:49:19 +0200"
let altRSSString = date.toRSS(alt: true) // "20 Jun 2017 14:49:19 +0200"

^ Top

To print a SQL formatted string from a date instance you need to use the .toSQL() function.

func toSQL() -> String

Examples:

let date = ... // 2015-11-19T22:20:40+01:00
let sqlString = date.toSQL() // "2015-11-19T22:20:40.000+01"

^ Top

Colloquial format allows you to produce a human friendly string as result of the difference between a date and a a reference date (typically now). Examples of colloquial formatted strings are 3 mins ago, 2 days ago or just now.

SwiftDate supports over 140+ languages to produce colloquial formatted strings; the entire engine behind the library is fully customizable so, if you need, you can override default strings and produce your own variants.

To print a colloquial variant of a string just call .toRelative() function from a Date or DateInRegion instance.

func toRelative(since: DateInRegion?, style: RelativeFormatter.Style?, locale: LocaleConvertible?) -> String

It takes three arguments:

  • since | DateInRegion?: reference date, if you omit it current date is set as reference date.
  • style | RelativeFormatter.Style?: the style used to print the formatted value. There are 3 styles: RelativeFormatter.defaultStyle(), RelativeFormatter.timeStyle() and RelativeFormstter.twitterStyle().
  • locale | LocaleConvertible?: pass non nil value to override the receiver region's locale and print the representation using passed locale.

Examples:

let ago5Mins = DateInRegion() - 5.minutes
let _ = ago5Mins.toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.italian) // "5 minuti fa"

let justNow2 = DateInRegion() - 2.hours
let _ = justNow2.toRelative(style: RelativeFormatter.twitterStyle(), locale: Locales.italian) // "2h fa"

let justNow = DateInRegion() - 10.seconds
let _ = justNow.toRelative(style: RelativeFormatter.twitterStyle(), locale: Locales.italian) // "ora"

You can fully customize the language and results. See the guide "Customize Colloquial Formatter".

^ Top

If you to format date with different date/time styles you can use the . dateTimeMixed formatter option where you can choose a format both for date and time (DateFormatter.Style).

// Just print full date with no time
let formatted = date.toString(.dateTimeMixed(dateStyle: .full, timeStyle: .none))

^ Top

Next Chapter: Time Interval Formatting