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.

Answered by Claude31 in 328406022

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"
Accepted Answer

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"
String To Date
 
 
Q