2016-11-25 6 views
2

時間が18:36の場合は12時間形式で現在の時刻を取得したい。06:35 PMのようにする必要があります。この目的のために、私は以下のコードを使用しましたが、それは私に必要なフォーマットを与えません。私はこのようなフォーマットを取得します。現在の時刻を12時間形式で取得するには?

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

dateFormatter.dateFormat = "hh:mm a"

dateFormatter.dateFormat = "h:mm a"をあなたが必要なものを見つけ出すためのもの: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は含まれません。簡単な修正ですが、フォーマット文字列を2番目の "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: だけの行に変更します。また、このサイトは素晴らしいですあなたのコード

+0

FYI - Swift 3を使用するには、 'NSDate'が' Date'でなければならず、 'NSDateFormatter'は' DateFormatter'である必要があります。そして、フォーマットはSwiftのバージョン間で変わらない。 – rmaddy

+0

working.iは試しました – Techiee

+0

あなたのコードで提案してください私は18:36として時間を得ることができますが、06:36 PMではありません – Techiee

関連する問題