NSDate如何在swift 2.2中添加不同的年/月

时间:2016-05-23 05:18:20

标签: ios swift2 nsdate nsdatecomponents

UITextField我输入的日期为43年零2个月 我会确保截至2016年1月1日的总和是43年2个月 01/01/2020从总和变为44年零5个月 01/01/2022从总和变为44年零8个月 等

这是我的代码 有人可以帮助我。

func upDateField(sender: UIDatePicker){


    inizioTextField.text = dateFormat.stringFromDate(sender.date)


    let currentDate = NSDate()

    let dateFormatter = NSDateFormatter()

    dateFormatter.locale = NSLocale.currentLocale()
    dateFormatter.locale = NSLocale(localeIdentifier: "it_IT")

    dateFormatter.dateStyle = NSDateFormatterStyle.LongStyle
    let strDate = dateFormatter.stringFromDate(datePicker.date)
    inizioTextField.text = strDate

    let yearsToAdd = 43
    let monthsToAdd = 2


    let newDateComponents = NSDateComponents()
    newDateComponents.year = yearsToAdd
    newDateComponents.month = monthsToAdd

    let calculatedDate = NSCalendar.currentCalendar().dateByAddingComponents(newDateComponents, toDate: datePicker.date, options: NSCalendarOptions.init(rawValue: 0))

    let resultDate = dateFormatter.stringFromDate(calculatedDate!)
    dateFormatter.dateStyle = NSDateFormatterStyle.LongStyle
    anticipoLabel.text =  "se tutto va bene dal \(resultDate) sei in pensione anticipata!"
    anticipoLabel.alpha = 1

}

感谢您的回答 我试图这样做但是我收到了这个错误:无法转换类型的值' NSDate?'期望参数类型Int in:case_where calculatedDate< 2016

我哪里错了? 这是修改后的代码。

var yearsToAdd = 0  var monthsToAdd = 0

    let newDateComponents = NSDateComponents()
    newDateComponents.year = yearsToAdd
    newDateComponents.month = monthsToAdd

    let calculatedDate = NSCalendar.currentCalendar().dateByAddingComponents(newDateComponents, toDate: datePicker.date, options: NSCalendarOptions.init(rawValue: 0))

    switch calculatedDate {
    case _ where calculatedDate < 2016 :
        yearsToAdd = 43
        monthsToAdd = 2

    case _ where calculatedDate < 2020 :
        yearsToAdd = 50
        monthsToAdd = 2

    default:
        break

    }

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题,你想根据当前年份添加不同的值,对吧?为了达到这个目的,你需要这样的东西:

let currentYear = NSCalendar.currentCalendar().component(.Year, fromDate: NSDate())

var yearsToAdd = 0
var monthsToAdd = 0

switch currentYear {
    case _ where currentYear < 2016 :
        yearsToAdd = 43
        monthsToAdd = 2
    case _ where currentYear < 2020 :
        // ... and so on
}
Swift中的{p> case陈述不会自动落空 请记住,这是一种非常天真的方法。谷歌翻译说你的代码示例中的字符串说明了#34;提前退休&#34; - 也许你的立法中有一个计算偏差的公式?