date(_:locale:timeZone:calendar:)
Creates a regex component that matches a localized date string formatted in accordance with a style, capturing it as a Foundation date.
Declaration
static func date(_ style: Date.FormatStyle.DateStyle, locale: Locale, timeZone: TimeZone, calendar: Calendar? = nil) -> Date.ParseStrategyParameters
- style:
A Datestyle to use when matching date substrings.
- locale:
The locale to use when matching date substrings. Matching uses this locale to evaluate the order of date components. It also uses the locale’s language for date format styles that use words.
- timeZone:
The time zone to use when returning a captured Date. The returned date’s time value is
00:00:00in this time zone. - calendar:
The calendar to use when matching date substrings. If
nil, matching uses the default calendar of the specifiedlocale.
Return Value
A RegexComponent that matches date substrings as Foundation Date instances.
Discussion
This method matches date substrings in accordance with the formatting of Foundation’s Date.FormatStyle.
If a time value follows the date substring, the matcher ignores it, treating it as any other character sequence. To match date and time substrings, use dateTime(date:time:locale:timeZone:calendar:).
The following example creates a Regex that matches a date formatted with the numeric style in the en_US locale. It then matches this regex against a source string containing a date with this format, some whitespace, a substring, more whitespace, and a currency value.
let source = "7/31/2022 Lemon-lime slushie $1.99"
let matcher = Regex {
Capture {
One(.date(.numeric,
locale: Locale(identifier: "en_US"),
timeZone: TimeZone(identifier: "PST")!))
}
}
guard let match = source.firstMatch(of: matcher) else { return }
let date = match.1 // date == Jul 31, 2022 at 12:00 AM PSTSee Also
Matching dates and times
date(format:locale:timeZone:calendar:twoDigitStartDate:)dateTime(date:time:locale:timeZone:calendar:)iso8601iso8601Date(timeZone:dateSeparator:)iso8601(timeZone:includingFractionalSeconds:dateSeparator:dateTimeSeparator:timeSeparator:)iso8601WithTimeZone(includingFractionalSeconds:dateSeparator:dateTimeSeparator:timeSeparator:timeZoneSeparator:)