0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Swift]SwiftDateライブラリを使用し特定の日付範囲かチェックさせる

Last updated at Posted at 2025-06-02

SwiftDateについて

今回は日付・時間処理ライブラリ SwiftDate について紹介します。
Swift には様々なライブラリがありますが、SwiftDate は 日付、時刻、タイムゾーン を解析、検証、操作、比較、表示するための便利なライブラリです。

参考文献

実際に使ってみる

CocoaPodsでインストールします。

pod 'SwiftDate'

指定された期間内かどうかを判定し、該当期間なら画像を表示し、そうでなければラベルを表示する という処理を行います。


import UIKit
import SwiftDate

class ViewController: UIViewController {

    @IBOutlet private weak var outOfPeriodLabel: UILabel!
    @IBOutlet private weak var dateRangeBackgroundImageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        bind()
    }

}

extension ViewController {
    func bind() {
        outOfPeriodLabel.isHidden = Date().isWithinVisibleDateRange()
        dateRangeBackgroundImageView.isHidden = !Date().isWithinVisibleDateRange()
    }
}

extension Date {
    func isWithinVisibleDateRange() -> Bool {
        return isInRange(
            date: DateInRegion("2025/06/01 10:00:00", region: .JST)!.date,
            and: DateInRegion("2025/06/30 23:59:59", region: .JST)!.date,
            orEqual: true,
            granularity: .second
        )
    }
}

extension Region {
    static let JST = Region(calendar: Calendars.gregorian, zone: Zones.asiaTokyo, locale: Locales.japanese)
}

isInRange(...) の引数解説

date:
→ 範囲の開始日

and:
→ 範囲の終了日

orEqual:
→ trueにすると開始日や終了日と同じであっても範囲内と見なすという意味です。falseにすると開始・終了と一致する値は除外されます。

granularity
.secondを指定。秒単位まで比較するという意味。

⏱️ granularity に指定できる単位一覧

意味
.era 紀元(例:西暦など)
.year
.month
.weekOfYear 年単位の週
.weekOfMonth 月単位の週
.day
.hour
.minute
.second
.nanosecond ナノ秒(最も細かい単位)

RegionでJSTの設定

RegionはSwiftDate によって提供される構造体で、カレンダー(暦)、タイムゾーン、ロケール(言語・地域設定)を1つにまとめたものです。

SwiftDate を使って日時を操作する際、「どの地域基準で処理するか」を明示的に指定することができます。

要素名 説明
calendar 暦(カレンダーの種類) グレゴリオ暦 (.gregorian)
timeZone タイムゾーン(時間帯) 日本標準時 (Asia/Tokyo)
locale 地域と言語(文化設定) 日本語 (ja_JP)

これを指定範囲内のチェックメソッドで利用し判定を行うようにしてます。

まとめ

実務では、キャンペーンやイベントに合わせたバナーの表示タイミングの制御などでよく使われます。
覚えておいて損はないライブラリです。

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?