Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current time in 12 hour format?

Tags:

date

ios

swift

I want get current time in 12 hour format.I want format if time is 18:36 then it should be like 06:35 PM. for this purpose i have used below code but it just don't give me required format.I get format like this.

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
let date22 = dateFormatter.string(from: date)
like image 457
TechChain Avatar asked Jan 05 '23 00:01

TechChain


2 Answers

Check out this date formatting guide. & this site.

let dateAsString = "6:35 PM"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "hh:mm a"
let date = dateFormatter.dateFromString(dateAsString)

dateFormatter.dateFormat = "HH:mm"
let date24 = dateFormatter.stringFromDate(date!)
like image 72
DeyaEldeen Avatar answered Jan 07 '23 12:01

DeyaEldeen


I also had the same problem(from my backend dateString is coming in 24 hours format and also in UTC), so I created a function it is working perfectly. See this function:-

func getRequiredFormat(dateStrInTwentyFourHourFomat: String) -> String? {

    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

    if let newDate = dateFormatter.date(from: dateStrInTwentyFourHourFomat) {

        let timeFormat = DateFormatter()
        timeFormat.timeZone = TimeZone.autoupdatingCurrent
        timeFormat.locale = Locale(identifier: "en_US_POSIX")
        timeFormat.dateFormat = "hh:mm a"

        let requiredStr = timeFormat.string(from: newDate)
        return requiredStr
    } else {
        return nil
    }
}
like image 30
Vipul Kumar Avatar answered Jan 07 '23 12:01

Vipul Kumar