2016-11-25 62 views
2

我想獲得12小時格式的當前時間。如果時間是18:36,我想要格式,那麼它應該是下午06:35。爲此,我使用了下面的代碼,但它只是不給我需要的格式。我得到這樣的格式。如何以12小時格式獲取當前時間?

let date = Date() 
let dateFormatter = DateFormatter() 
dateFormatter.dateFormat = "h:mm a" 
let date22 = dateFormatter.string(from: date) 
+1

此外,這個網站是一個偉大的找出你需要的東西:http://nsdateformatter.com/ – Losiowaty

+0

你的問題不清楚。什麼是原始時間輸入?一個'String'或一個'Date'? – rmaddy

回答

4

看看這個日期格式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!) 
+1

可能值得一提的是,OP想要的是帶有前導0的小時格式,而且這個答案(雖然完全正確)不包括前導0.簡單的修復,但只是添加第二個「h」,以便格式字符串是「hh:mm a」。 –

+0

是的,謝謝,只是修好了。 – DeyaEldeen

1

SWIFT 2:

let date = NSDate() // return current time and date 
    let dateFormatter= NSDateFormatter() 
    dateFormatter.dateFormat = "hh:mm a" // for specifying the change to format hour:minute am/pm. 
    let dateInString = dateFormatter.stringFromDate(date) // provide current time in string formatted in 06:35 PM if current time is 18:35 

    print(dateInString) 

SWIFT 3: 只需更改行:

dateFormatter.dateFormat = "h:mm a"dateFormatter.dateFormat = "hh:mm a"

在你的代碼

+0

僅供參考 - 要使用Swift 3,'NSDate'需要'Date','NSDateFormatter'需要'DateFormatter'。並且格式在Swift版本之間不會改變。 – rmaddy

+0

不working.i已嘗試 – Techiee

+0

請建議您的代碼我可以得到時間爲18:36但不是06:36 PM – Techiee

相關問題