2015-12-27 30 views
2

我有模擬器在美國的位置和日曆類型爲格里高利。 UIDatePicker以12小時格式顯示時間;但是當我更新timeLabel時,我看到時間是在軍事時間。我想知道爲什麼這樣?我可以通過創建一個從軍事轉換爲12小時的功能來快速解決此問題,但如果用戶確實需要軍事時間,我不想幹預這一點。NSCalendar顯示爲軍事時間,但位置正在使用12小時時間(Swift/iOS)

@IBAction func timePicked(sender: UIDatePicker) 
    { 
     let date = sender.date 
     let calendar = NSCalendar.currentCalendar() 
     let components = calendar.components([.Hour, .Minute], fromDate: date) 
     day.hours = components.hour 
     day.minutes = components.minute 
     updateTimeLabel() 
    } 

編輯:

func updateTimeLabel() 
    { 
     self.timeLabel?.text = "Notify me at: " + day.description 
    } 

隨着day是顯示其形式一小時一小時和分鐘的對象:既然你說他們可能想無論是24小時或12小時分鐘

+0

您可以顯示'updateTimeLabel代碼'? – tktsubota

回答

1

,給他們選擇。

這樣你可以在24小時或12小時顯示代碼。

class ViewController: UIViewController { 
    @IBOutlet weak var timeLabel: UILabel! 

    @IBOutlet weak var twentyFourHours: UISwitch! 

    let dateFormatter = NSDateFormatter() 

    @IBOutlet weak var myDatePicker: UIDatePicker! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     timeMode(twentyFourHours) 


    } 

    @IBAction func datePicker(sender: UIDatePicker) { 

     let stringDate = dateFormatter.stringFromDate(myDatePicker.date) 
     self.timeLabel.text = stringDate 


    } 

    @IBAction func timeMode(sender: UISwitch) { 

    if twentyFourHours.on { 
     dateFormatter.dateFormat = "HH:mm" 

    } else { 

     dateFormatter.dateFormat = "hh:mm a" 


     } 

    datePicker(myDatePicker) 

    } 


    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


} 

以上作品在我的快速測試中僅僅是一個例子。注意我正在使用格式化程序來爲標籤和UISwtch做格式,供用戶選擇24小時或12小時。

12的格式是"hh:mm a"上月底一個是,如果顯示AM/PM


enter image description here


enter image description here

+0

感謝您的詳細解答!在你的例子中,日期選擇器保持12小時的時間,因爲它檢測到具有相應時間格式的區域。我想知道是否有一種方式來訪問數據,告訴它是否是12/24小時?或者如果日期選擇器可以更改爲24小時制? – stumped

+0

不錯的時間選擇 – 9BallOnTheSnap

相關問題