简体   繁体   English

将datePicker日期和计时器与用户Date和Time匹配(swift3)

[英]match datePicker date and timer with users Date and Time (swift3)

My code below creates a date picker and has it select a date and time. 我下面的代码创建一个日期选择器,并选择一个日期和时间。 All I want to do is when the date picker's date and time match the user's phone's date and time is to print the line "cool". 我要做的就是当日期选择器的日期和时间与用户电话的日期和时间匹配时,将打印“ cool”行。 That's it. 而已。 I commented the line that is causing me problems. 我评论了导致我出现问题的那一行。

import UIKit

var dateFormatter : DateFormatter!

let datePicker2 = UIDatePicker();
let date = Date()

class ViewController: UIViewController {

    @IBOutlet var dateLabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()

        let datePicker : UIDatePicker = UIDatePicker(frame: CGRect(x: 0,y: 330,width: self.view.frame.size.width,height: 220))
        datePicker.datePickerMode = UIDatePickerMode.dateAndTime
        self.view.addSubview(datePicker)

        datePicker.addTarget(self, action: #selector(ViewController.change(_:)), for: UIControlEvents.valueChanged)

        dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "YYYY-MM-dd hh:mm"
    }

    @IBAction func change(_ sender : UIDatePicker)
    {
        dateLabel.text = dateFormatter.string(from: sender.date)
        ///print cool line; what I have does not work
        if dateLabel.text == String(describing: date){
            print("cool")

        }
    }
}

Your primary issue is how you compare the two dates. 您的主要问题是如何比较两个日期。 You should be using the same date formatter to convert both Date instances to strings in the same format. 您应该使用相同的日期格式化程序将两个Date实例转换为相同格式的字符串。 Then you can compare the two strings. 然后,您可以比较两个字符串。

@IBAction func change(_ sender : UIDatePicker)
{
    let pickerString = dateFormatter.string(from: sender.date)
    let nowString = dateFormatter.string(from: Date())

    dateLabel.text = pickerString
    if pickerString == nowString {
        print("cool")
    }
}

You are also using the wrong format. 您还使用了错误的格式。 You need "yyyy-MM-dd HH:mm" . 您需要"yyyy-MM-dd HH:mm" YYYY is slightly different. YYYY略有不同。 You always want yyyy unless you have a clearly understood and specific need to use YYYY . 除非您有明确的特定使用YYYY需要,否则您总是希望yyyy And for the hour you want HH instead of hh . 对于一个小时,您要使用HH而不是hh HH is a 24-hour hour while hh is a 12-hour hour. HH是24小时,而hh是12小时。 Only use hh is you also use a (for AM/PM). 只使用hh是你也可以使用a (用于AM / PM)。

And your properties should be inside the class, not outside. 并且您的属性应该在类内部,而不是外部。

Move datePicker2 inside the class. 在类中移动datePicker2

date is now obsolete based on my answer so you can remove it completely. 根据我的回答, date现在已过时,因此您可以将其彻底删除。

dateFormatter should also be moved inside the class. dateFormatter也应该在类内移动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM