user6032625
user6032625

Reputation: 197

How can I convert the 24 hour time format to 12 hour time format?

I can get the 24 hour style time, but how do I get the 12 hour format with the am and pm?

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Hour, .Minute, .Second], fromDate: date)
let hour = components.hour
let minutes = components.minute

Upvotes: 4

Views: 11303

Answers (4)

Satabhisha Roy
Satabhisha Roy

Reputation: 1

   let str=dict["startDateTime"] as! String //if the date is in the array
   let str="16:00" //if you want to use static date
    let index=str.index(str.startIndex, offsetBy: 11)
    let end_index=str.index(str.endIndex, offsetBy:-3)
    let dateAsString = str[index ..< end_index]
    let dateFormatter=DateFormatter()
    dateFormatter.dateFormat="HH:mm"

    let date = dateFormatter.date(from: String(dateAsString))
    dateFormatter.dateFormat = "h:mm a"
    let Date12 = dateFormatter.string(from: date!)
    print(Date12)

Upvotes: 0

Dilip Bhuva
Dilip Bhuva

Reputation: 180

Time format must be in 'hh' not HH

formatter.dateFormat = "hh:mm a"

Upvotes: 3

Muzahid
Muzahid

Reputation: 5186

As you say, you should use NSDateFormatter for your desired format. Hope this will help you.

let date = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "hh:mm a"
let time = formatter.stringFromDate(date)

For more information about date formatter see NSDateFormatter

Upvotes: 6

Brian Bird
Brian Bird

Reputation: 1206

Swift 3.1 Answer

 let date = Date()                //Jun 1, 2017, 10:22 AM"
 let formatter = DateFormatter()  //<NSDateFormatter: 0x608000244380>
 formatter.dateFormat = "hh:mm a" //<NSDateFormatter: 0x608000244380>
 let time = formatter.string(from: date) //"10:22 AM"

Upvotes: 3

Related Questions