Search code examples
swiftswift-regexbuilder

Swift RegexBuilder convert date String to Date


I know the usual way of using DateFormatter style with option of .withFullDate to convert a date of style "yyyy-MM-dd" (ISO 8601 but just date, not time or timezone) into Swift Date

let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withFullDate]
let date = formatter.date(from: "2023-10-21")

But I am wondering if it is possible to achieve this with new Swift's RegexBuilder Capture and maybe with Transform? It seems the .date(...) function requires locale but I do not care for the locale, I just want a String date to convert into Date.

Is it possible to do this using built in date formatter in RegexBuilder? i.e. without writing literal Regex.


Solution

  • You can capture the date string as a Date directly

    One(.iso8601.year().month().day().dateSeparator(.dash))
    

    Example

    let input = "2023-10-21 some other stuff"
    
    let regex = Regex {
        Capture {
            One(.iso8601.year().month().day().dateSeparator(.dash))
        }
        OneOrMore(.any)
    }
    
    if let match = input.firstMatch(of: regex) {
        print(match.output.1, type(of: match.output.1))
    }
    

    2023-10-21 00:00:00 +0000 Date