2015-01-05 14 views
5

文字列によって与えられた与えられた日付から月と日の数が必要です。IOS Swift。時間から日付

dが、私は理想的な日から月、日、分たいと思いますが、私はこのエラーを渡され得れば、私はその部分を動作する日付の文字列

let dateFormatter = NSDateFormatter() 
    dateFormatter.dateFormat = "MM-dd-yy" 
    let date = dateFormatter.dateFromString(d) 
    startTime = date?.timeIntervalSinceReferenceDate 

です。コンパイラは最後の行について不平を言っています。あなたは月と日の面で違いを計算するためにNSCalendarを使用する必要が

おかげ

+0

startTime'はオプションとして宣言 'ですか? –

+0

エラーは何ですか? – Fogmeister

答えて

7

。例:(2014年1月5日に)

let calendar = NSCalendar.autoupdatingCurrentCalendar() 
calendar.timeZone = NSTimeZone.systemTimeZone() 
let dateFormatter = NSDateFormatter() 
dateFormatter.timeZone = calendar.timeZone 
dateFormatter.dateFormat = "yyyy-MM-dd" 
if let startDate = dateFormatter.dateFromString("2014-9-15") { 
    let components = calendar.components([ .Month, .Day ], 
     fromDate: startDate, toDate: NSDate(), options: []) 
    let months = components.month 
    let days = components.day 
    print("It's been \(months) months and \(days) days.") 
} 

出力:

It's been 3 months and 21 days. 
+0

私は、Swiftのアップデートがこれを変更したと信じています。主に、or演算子が列挙型で動作しなくなりました。素晴らしい解決策!ありがとう – Unome

関連する問題