NSDateFormatterに問題があります。 2つの日付を選択してこれらの2つの日付の差を計算し、差を返す日付ピッカーを実装しました。しかし、それはこれらの2つの値は、メソッドがnil
を返し、NSDate
の型に変換されてcalculateDifference()
呼び出された関数内の部分になったときNSDateFormatterの問題.dateFromString使用時にnilを返します。
var firstDate = "Nov 3, 2016"
var lastDate = "Nov 9, 2016"
:二つの日付は、次の形式(.MediumStyle)です。次のように
私のコードは次のとおりです。
@IBOutlet weak var startDateOutput: UILabel! // shows start date user picked
@IBOutlet weak var endDateOutput: UILabel! // shows end date user picked
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var answerFieldTimeDifference: UILabel! // Output Field
var firstDate = ""
var lastDate = ""
@IBAction func startButton(sender: AnyObject) // Button to set firstDate
{
firstDate = NSDateFormatter.localizedStringFromDate(datePicker.date, dateStyle: NSDateFormatterStyle.MediumStyle, timeStyle: NSDateFormatterStyle.NoStyle)
startDateOutput.text = firstDate
calculateDifference()
}
@IBAction func expirationButton(sender: AnyObject) // Button to set lastDate
{
lastDate = NSDateFormatter.localizedStringFromDate(datePicker.date, dateStyle: NSDateFormatterStyle.MediumStyle, timeStyle: NSDateFormatterStyle.NoStyle)
endDateOutput.text = lastDate
calculateDifference()
}
func calculateDifference()
{
if !firstDate.isEmpty && !lastDate.isEmpty
{
let dateFormatter = NSDateFormatter()
let firstDateAsNSDate = dateFormatter.dateFromString(firstDate) //returns nil
let lastDateAsNSDate = dateFormatter.dateFromString(lastDate) //returns nil
let dateComponentsFormatter = NSDateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [NSCalendarUnit.Day]
var calculatedDifference = dateComponentsFormatter.stringFromDate(firstDateAsNSDate!, toDate: lastDateAsNSDate!)
answerFieldTimeDifference.text = calculatedDifference
}
}
を追加します。 2つの 'NSDate'オブジェクトへの参照を保持してください。 – rmaddy