String To Date

I need to Convert a String like "Today At 11 AM" To a Date or is it Even Possible. Thanks in advance.

Accepted Reply

KMT suggestion works well:


Test in playground:


let aFormatter = DateFormatter()
let dateForTest = Date()                   // "Aug 27, 2018 at 11:11 AM"  The original format
aFormatter.dateFormat = "EEE MMM dd, yyyy 'At' hh a"       // At must be quoted ; yyyy needed otherwise, at the end you get year 2000
aFormatter.amSymbol = "AM"
aFormatter.pmSymbol = "PM"
let aDay = aFormatter.string(from: dateForTest)    // "Mon Aug 27, 2018 At 11 AM"  The specific format
let readDate = aFormatter.date(from: aDay)   //  a Date  "Aug 27, 2018 at 11:11 AM"


But do you really want to parse with Today in the string ?

Then you have to convert Today (if Today is effectively today and not yesterday !)


let todayFormatter = DateFormatter()
let today = Date()
todayFormatter.dateFormat = "EEE MMM dd, yyyy"
let todayConverted = todayFormatter.string(from: today)
var myString = "Today At 11 AM"
myString = myString.replacingOccurrences(of: "Today", with: todayConverted)
let theDateIWant = aFormatter.date(from: myString)     // a Date "Aug 27, 2018 at 11:00 AM"

Replies

Perhaps this applies?


https://stackoverflow.com/questions/4380381/convert-string-to-date-in-my-iphone-app

KMT suggestion works well:


Test in playground:


let aFormatter = DateFormatter()
let dateForTest = Date()                   // "Aug 27, 2018 at 11:11 AM"  The original format
aFormatter.dateFormat = "EEE MMM dd, yyyy 'At' hh a"       // At must be quoted ; yyyy needed otherwise, at the end you get year 2000
aFormatter.amSymbol = "AM"
aFormatter.pmSymbol = "PM"
let aDay = aFormatter.string(from: dateForTest)    // "Mon Aug 27, 2018 At 11 AM"  The specific format
let readDate = aFormatter.date(from: aDay)   //  a Date  "Aug 27, 2018 at 11:11 AM"


But do you really want to parse with Today in the string ?

Then you have to convert Today (if Today is effectively today and not yesterday !)


let todayFormatter = DateFormatter()
let today = Date()
todayFormatter.dateFormat = "EEE MMM dd, yyyy"
let todayConverted = todayFormatter.string(from: today)
var myString = "Today At 11 AM"
myString = myString.replacingOccurrences(of: "Today", with: todayConverted)
let theDateIWant = aFormatter.date(from: myString)     // a Date "Aug 27, 2018 at 11:00 AM"