简体   繁体   English

获得两个日期的差异 - 斯威夫特

[英]Getting the difference in two dates - Swift

I cannot get the date difference function to work. 我不能让日期差异功能起作用。 It says NSDate is not implicitly convertible to 'Date' but I do not see an immediate work around this; 它说NSDate不能隐含地转换为'Date',但我没有看到立即解决这个问题; using as Date does not work. 使用as Date不起作用。

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var dateLabelOutlet: UILabel!

    let currentDate = NSDate()
    let dateFormatter = DateFormatter()

    let userCalendar = NSCalendar.current

    let requestedComponent: NSCalendar.Unit = [
        NSCalendar.Unit.month,
        NSCalendar.Unit.day,
        NSCalendar.Unit.hour,
        NSCalendar.Unit.minute,
        NSCalendar.Unit.second,

    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    func printTime(){
        dateFormatter.dateFormat = "dd/MM/yy hh:mm:ss a"
        let startTime = NSDate()
        let endTime = dateFormatter.date(from: "25/12/16 00:00:00")

        let timeDifference = userCalendar.components(requestedComponent, from: startTime, to: endTime!, options: [])

        dateLabelOutlet.text = "\(timeDifference.month) Months \(timeDifference.day) Days \(timeDifference.minute) Minutes \(timeDifference.second) Seconds"
    }

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

Change all of your NSDate to Date , then replace your requestedComponent with this: 将所有NSDate更改为Date ,然后用以下内容替换您的requestedComponent

let requestedComponent: Set<Calendar.Component> = [ .month, .day, .hour, .minute, .second]

Your difference will be: 你的区别将是:

let timeDifference = userCalendar.dateComponents(requestedComponent, from: startTime, to: endTime!)

FYI: Your dateFormatter doesn't work with this "25/12/16 00:00:00" here is your whole class in correct form: 仅供参考:您的dateFormatter无法使用此“25/12/16 00:00:00”这里是您的全班正确形式:

class ViewController: UIViewController {

    @IBOutlet weak var dateLabelOutlet: UILabel!

    let currentDate = Date()
    let dateFormatter = DateFormatter()

    let userCalendar = Calendar.current

    let requestedComponent: Set<Calendar.Component> = [.month,.day,.hour,.minute,.second]

    override func viewDidLoad() {
        super.viewDidLoad()
         // Do any additional setup after loading the view, typically from a nib.
    }

    func printTime() {
        dateFormatter.dateFormat = "dd/MM/yy hh:mm:ss"
        let startTime = Date()
        let endTime = dateFormatter.date(from: "25/12/16 00:00:00")
        let timeDifference = userCalendar.dateComponents(requestedComponent, from: startTime, to: endTime!)

        dateLabelOutlet.text = "\(timeDifference.month) Months \(timeDifference.day) Days \(timeDifference.minute) Minutes \(timeDifference.second) Seconds"
    }

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

I think it will be helpfull.It will print all months between from and two dates 我认为这将有所帮助。它将打印从两个日期到两个日期之间的所有月份

   let dateFormtter = DateFormatter()
    dateFormtter.dateFormat = "yyyy-MM-dd"

    let startDate = dateFormtter.date(from: fromTF.text!)
    let endDate = dateFormtter.date(from: toTF.text!)

 func getMonthAndYearBetween(from start: String, to end: String) - > 
[String] {

    let format = DateFormatter()
    format.dateFormat = "yyyy-MM-dd"

    guard let startDate = format.date(from: start),
        let endDate = format.date(from: end) else {
            return []
    }

    let calendar = Calendar(identifier: .gregorian)
    let components = calendar.dateComponents(Set([.month,.day]), 
   from: startDate, to: endDate)

    var allDates: [String] = []
    let dateRangeFormatter = DateFormatter()
    dateRangeFormatter.dateFormat = "yyyy-MM-dd"

    for i in 0 ... components.month! {
        guard let date = calendar.date(byAdding: .month , value: i, to: startDate) else {
            continue
        }

        let formattedDate = dateRangeFormatter.string(from: date)
        allDates += [formattedDate]

        print(allDates)
    }
    return allDates
}

Call above method like this 像这样调用上面的方法

     print(getMonthAndYearBetween(from: fromTF.text!, to: 
                    toTF.text!))

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

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