Search code examples
iosswiftdate-formatting

Convert 24 Hour Time Date Object into 12 Hour Time Date Object


I'm simply trying to turn a Date object when a user has "24 hour time" enabled on their iPhone into a "12 hour time" Date Object.

I've tried this as stated in previous threads regarding this issue, but I've had no luck:

Initial finalDate object: Date 2017-08-30 22:00:00 UTC

 let dateFormatter = DateFormatter()
 dateFormatter.locale = Locale(identifier:"en_US")
 dateFormatter.dateFormat = "MM/dd/yyyy h:mm a"
 let dateString = dateFormatter.string(from: finalDate)
 let theFinalConvertedDate = dateFormatter.date(from: dateString)

What I end up with:

    theFinalConvertedDate   Date? 2017-08-30 22:00:00 UTC

I am not sure why this is happening considering that dateString prints out to be:

"08/30/2017 5:00 PM"    

So it does initially convert it to the expected output, but theFinalConvertedDate ends up being Date? 2017-08-30 22:00:00 UTC


Solution

  • It makes no sense whatsoever to attempt to change the format of a Date object. A Date has no format. You only get a string in some desired format by using DateFormat to convert the Date to a String.

    Logging a Date always shows the date value in the UTC timezone with a fixed format.

    All you need is:

    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier:"en_US_POSIX")
    dateFormatter.dateFormat = "MM/dd/yyyy h:mm a"
    let dateString = dateFormatter.string(from: finalDate)
    

    dateString is the value you care about. This will be in the desired format.

    And note that you need to use en_US_POSIX to ensure the result isn't affected by the user's time settings on the iOS device.