I want to change the formate of string date to get just a month name in string.
I want to change from "yyyy-MM-dd HH:mm:ss" to "MMMM" format
like the code below :
func changeFormat(of dateTime: String, fromFormat format1: String = "yyyy-MM-dd HH:mm:ss", toFormat format2: String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format1
guard let originDate = dateFormatter.date(from: dateTime) else {
return nil
}
dateFormatter.dateFormat = format2
let newFormattedDate = dateFormatter.string(from: originDate)
return newFormattedDate
}
// usage
changeFormat(of "2018-04-12 11:52:12", toFormat : "MMMM")
the code above will run as expected if the date time format in the device is set to 24 hours format (Settings -> General -> Date & Time -> 24-Hour Time) like below
but if i switch off the 24-Hour Time (12-Hour time format is activated), the function will return nil in this line
guard let originDate = dateFormatter.date(from: dateTime) else {
return nil
}
I want that function to work either in 24-Hour Time or 12-Hour Time, so the user doesn't need to manually change their settings.
what should I do ?