1

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

enter image description here

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 ?

Alexa289
  • 8,089
  • 10
  • 74
  • 178

1 Answers1

2

If you want it to work regardless of your device's regional settings, you need to set the locale property of your DateFormatter

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = format1

It is important to set the locale before you set dateFormat

mag_zbc
  • 6,801
  • 14
  • 40
  • 62