NSCalendar显示为军事时间,但位置使用12小时时间(Swift / iOS)

时间:2015-12-27 02:09:06

标签: ios swift date time uidatepicker

我有模拟器在美国的位置,日历类型为Gregorian。 UIDatePicker以12小时格式显示时间;但是当我更新timeLabel时,我发现时间是军事时间。我想知道为什么会这样?我可以通过创建一个从军事转换到12小时的功能来快速解决这个问题,但是如果用户确实需要军事时间,我不想干涉它。

@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是一个对象,以小时:分钟

的形式显示其小时和分钟

1 个答案:

答案 0 :(得分:1)

既然你说他们可能需要24小时或12小时,请给他们选择。

这样你就可以在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" a的结尾是否显示AM / PM

enter image description here

enter image description here