Vivek
Vivek

Reputation: 5213

Date not convert in AM/PM Format in swift

I need to date and time with my own format like time in AM/PM (12 hours).

extension Date {
func getStringFromDateWithUTCFormat() -> ObjTimeStamp {
                
        let dateFormatterPrint = DateFormatter()
        dateFormatterPrint.timeZone = TimeZone.init(abbreviation: "UTC")
        
        // Get Date
        dateFormatterPrint.dateFormat = "MM/dd/yyyy" //"MMM dd,yyyy"
        let date = dateFormatterPrint.string(from: self)
        
        // Get Time
        dateFormatterPrint.dateFormat = "hh:mm:ss a"
        let time = dateFormatterPrint.string(from: self)
        
        return ObjTimeStamp.init(date: date, time: time, timeStamp: self)
    }   
}

Update

Calling function

self.currentDate = Date()
let objTimeStamp = currentDate.getStringFromDateWithUTCFormat() 

Perfect work when device time in 12-hour format when I try to change device time in 24-hour formate then given wrong time format.

enter image description here

Upvotes: 0

Views: 2730

Answers (1)

SM Abu Taher Asif
SM Abu Taher Asif

Reputation: 2331

set your dateFormatter locale to en-US then try to convert, it's works for me when iPhone's time format is 24 hour:

let date = Date()              
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en-US")
formatter.dateFormat = "hh:mm a"
let time12 = formatter.string(from: date)
print(time12)

output:

01:37 PM

Upvotes: 4

Related Questions