日付けの比較方法がわからず困っています。
実現したいことは、入力された年月(yyyy/MM)と現在の年月 (yyyy/MM)を比較して2年以上経過しているを判定することです。
・NSTimeInterval
・NSCalendar
・NSDateComponents
上記のこれらを使用するのでしょうか?
よろしくお願い致します。
気になる質問をクリップする
クリップした質問は、後からいつでもMYページで確認できます。
またクリップした質問に回答があった際、通知やメールを受け取ることができます。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
回答2件
0
ベストアンサー
Playground
で色々試してみてください。
NSCalendar
を使うのに NSDateComponents
を作らなくても良いのは便利ですねえ。
おまけの部分は下記のような文字列を返します。
"3 years, 3 weeks, 5 days, 10 hours, 27 minutes, 51 seconds"
これを用いて判定するのもアリでしょう。
swift
1//: Playground - noun: a place where people can play 2 3import UIKit 4 5// 入力年月用書式設定 6let dateFormatter = NSDateFormatter() 7dateFormatter.dateFormat = "yyyy/MM" 8let inputDate = dateFormatter.dateFromString("2012/11") 9 10// 入力年月の2年後 11let inputDateAfterTwoYears = NSCalendar.currentCalendar().dateByAddingUnit(.Year, value: 2, toDate: inputDate!, options: NSCalendarOptions.init(rawValue: 0)) 12 13// 現在の年月 14var currentDate = NSDate() 15 16// 現在の年月の2年前 17var todayBeforeTwoYears = NSCalendar.currentCalendar().dateByAddingUnit(.Year, value: -2, toDate: currentDate, options: NSCalendarOptions.init(rawValue: 0)) 18 19// 入力年月の2年後と現在の年月の比較 20let compareResult = NSCalendar.currentCalendar().compareDate(inputDateAfterTwoYears!, toDate: currentDate, toUnitGranularity: .Month) 21if compareResult == NSComparisonResult.OrderedAscending { 22 print("inputDateAfterTwoYears < currentDate") 23} else if compareResult == NSComparisonResult.OrderedDescending { 24 print("inputDateAfterTwoYears > currentDate") 25} else { 26 print("inputDateAfterTwoYears == currentDate") 27} 28 29// おまけ 30let dateComponentsFormatter = NSDateComponentsFormatter() 31dateComponentsFormatter.unitsStyle = NSDateComponentsFormatterUnitsStyle.Full 32 33let interval = currentDate.timeIntervalSinceDate(inputDate!) 34dateComponentsFormatter.stringFromTimeInterval(interval)
投稿2015/11/28 01:33
総合スコア1698
あなたの回答
tips
太字
斜体
打ち消し線
見出し
引用テキストの挿入
コードの挿入
リンクの挿入
リストの挿入
番号リストの挿入
表の挿入
水平線の挿入
プレビュー
質問の解決につながる回答をしましょう。 サンプルコードなど、より具体的な説明があると質問者の理解の助けになります。 また、読む側のことを考えた、分かりやすい文章を心がけましょう。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/11/28 01:51