0
0

iOS来月先月を取得する方法

Posted at

来月先月を取得する方法です

完成イメージ

sumplee.gif

DateComponentsを使って現在の年月を表示する

こちらの記事の続きになります。

実装方法

NextLastDateViewModel.swift
class NextLastDateViewModel: ObservableObject {
    @Published var text: String = ""
    var component: DateComponents
    
    init() {
        component = Calendar.current.dateComponents(in: TimeZone.current, from: Date())
        text = component.getYearMonthFormat()
    }

    func onTapNext() {
        let calendar = Calendar(identifier: .gregorian)
        let date = calendar.date(from: component)!
        let addMonth = DateComponents(month: 1, day: 0)
        let nextMonth = calendar.date(byAdding: addMonth, to: date)!
        component = Calendar.current.dateComponents(in: TimeZone.current, from: nextMonth)
        text = component.getYearMonthFormat()
    }

    func onTapLast() {
        let calendar = Calendar(identifier: .gregorian)
        let date = calendar.date(from: component)!
        let addMonth = DateComponents(month: -1, day: 0)
        let lastMonth = calendar.date(byAdding: addMonth, to: date)!
        component = Calendar.current.dateComponents(in: TimeZone.current, from: lastMonth)
        text = component.getYearMonthFormat()
    }
}

コード説明

重要なところだけ説明します。
getYearMonthFormatについては上記記載のあるリンクの前回を確認してください。
DateComponentsを変数で持っておきます。
onTapNext()は来月のボタンを押したらの処理です。
onTapLast()は先月のボタンを押したらの処理です。
DateComponents(month: -1, day: 0)
DateComponents(month: 1, day: 0)
こちらで先月、来月にしています。
これを利用すれば来年、明日なども可能になります。
UIは自分で好きなように作成してください!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0