前提・実現したいこと
現在の日付から1年前と1年後を計算して
その間の日付の年月を取得したいのですが
いまいち書き方がわからなかったのでご教示頂きたいです。
欲しい値としては(年,月)を(Int,Int)の配列で取得したいです。
実行結果で言うところ26以下の部分の情報は不要です。
該当のソースコード
Swift
1let calendar = Calendar.current 2let date = Date() 3let oneYearAgoDate = calendar.date(byAdding: .year, value: -1, to: date)! 4let oneYearLaterDate = calendar.date(byAdding: .year, value: 1, to: date)! 5let oneYearLaterDateMonth = calendar.component(.month, from: oneYearLaterDate) 6let oneYearLaterDateYear = calendar.component(.year, from: oneYearLaterDate) 7 8var tmpDate = oneYearAgoDate 9var month = calendar.component(.month, from: tmpDate) 10var year = calendar.component(.year, from: tmpDate) 11 12while( oneYearLaterDateMonth != month || oneYearLaterDateYear != year ){ 13 let addedDate = calendar.date(byAdding: .month, value: 1, to: tmpDate)! 14 print(addedDate) 15 tmpDate = addedDate 16 17 month = calendar.component(.month, from: addedDate) 18 year = calendar.component(.year, from: addedDate) 19}
実行結果
2017-11-26 05:51:04 +0000 2017-12-26 05:51:04 +0000 2018-01-26 05:51:04 +0000 2018-02-26 05:51:04 +0000 2018-03-26 05:51:04 +0000 2018-04-26 05:51:04 +0000 2018-05-26 05:51:04 +0000 2018-06-26 05:51:04 +0000 2018-07-26 05:51:04 +0000 2018-08-26 05:51:04 +0000 2018-09-26 05:51:04 +0000 2018-10-26 05:51:04 +0000 2018-11-26 05:51:04 +0000 2018-12-26 05:51:04 +0000 2019-01-26 05:51:04 +0000 2019-02-26 05:51:04 +0000 2019-03-26 05:51:04 +0000 2019-04-26 05:51:04 +0000 2019-05-26 05:51:04 +0000 2019-06-26 05:51:04 +0000 2019-07-26 05:51:04 +0000 2019-08-26 05:51:04 +0000 2019-09-26 05:51:04 +0000 2019-10-26 05:51:04 +0000
具体的に「いまいち書き方がわからなかった」のはどんな処理でしょうか?(現状のコードで何か問題はありますか?)
コメントありがとうございます。具体的には計算で求めた1年前と1年後の間に当たるDate型の日付の求め方が、上記の書き方だと単調だと思ったので、もっと簡潔に求めることが出来る方法がないかと思い質問させて頂きました。
なるほど。で、「現在の日付から1年前と1年後」というのは、今日が2018-10-26だとして、2017-11から2019-10までで良いのでしょうか? 2017-10が抜けていますが、意図したものですか?
意図したものではないですね・・・。2017-10〜2019-10で取得がしたいです。
回答2件
あなたの回答
tips
プレビュー