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

2020-03-06 08:05发布

问题:

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

回答1:

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



回答2:

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"


回答3:

Time format must be in 'hh' not HH

formatter.dateFormat = "hh:mm a"


回答4:

   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)


标签: ios swift nsdate