Search code examples
iosswift3nsdateformatterswiftdate

Swift string convert to SwiftDate


How can I convert 12 Oct 2018 at 10:45:46 AM to SwiftDate DateInRegion? My code returns nil:

    let ds = "12 Oct 2018 at 10:45:46 AM"
    let region = Region(tz: TimeZone.current,
                        cal: CalendarName.gregorian.calendar,
                        loc: Locale.init(identifier: "en"))
    let format = DateFormat.custom("EEE, dd MM yyyy HH:mm:ss zzz")
    var str = ds.date(format: format, fromRegion: region)

Solution

  • check your dateformat , is not available, the correct format is

    let ds = "12 Oct 2018 at 10:45:46 AM"
    let format = DateFormat.custom("dd MMM yyyy 'at' HH:mm:ss a")
    

    for additional info you get old answered from SO.for dateformats you get detailed answer from here