You are correctly parsing the string to the Date
object. The way it is presented by the print
is because by default if printing an object, its description
is printed. In case of Date
, it will be always the format you get. But the date is correct.
If you want to get it presented the way it was before, again use the same dateFormatter
and just format the date to string back:
NSLog(@"result date: %@", [df stringFromDate:resultDate]);
UPDATE
If the problem is the hour shift, that’s due to your current timezone that will be used when parsing using DateFormatter
. To overcome this, set explicitly timezone and locale of the date formatter, see this example (swift version, but you need just those two line with setting timeZone
and locale
on dateFormatter):
let dateString = "3/2/2018 11:44:32 AM"
let df = DateFormatter()
df.dateFormat = "MM/d/yyyy h:mm:ss a"
// set the timezone and locale of the dateformatter:
df.timeZone = TimeZone(identifier: "GMT")
df.locale = Locale(identifier: "en_US_POSIX")
let date = df.date(from: dateString)
// now it will print as you expect:
print(date)
7
solved Convert String to Date in Objective-C [duplicate]