swiftnsdateformatternsdatecomponentsnsdatepicker

How can i Convert (2020-02-21 06:07:21 +0000) to "21 Feb 2021 12:00 AM"?


I am using device time to get date components. this works fine for 12 hours formate but if user changes device time to 24 hours it shows wrong calculations. used the following method to convert but it always return nil.

            let dateAsString = "\(Date())"
            let df = DateFormatter()
            df.dateFormat = "yyyy-mm-dd HH:mm:ss zzz"

            let date = df.date(from: dateAsString)
            df.dateFormat = "d MMM yyyy h:mm a"

            let time12 = df.string(from: date!)
            print(time12)

Solution

  • I have just tried below it works fine on both cases. with AM or PM or 24Format and if you remove a in formatter.dateFormat = "dd MMM yyyy HH:mm a" gives you 24 Format. Even I am using this in my code.

    let someDate = Date()
    let formatter = DateFormatter()
    formatter.dateFormat = "dd MMM yyyy HH:mm a"
    let someDateTime = formatter.string(from: someDate)
    print(someDateTime)
    

    Print:

    21 Feb 2020 09:35 AM