LoginSignup
128
122

More than 5 years have passed since last update.

Swift 3 の日時操作チートシート

Last updated at Posted at 2016-10-10

Dateの操作でよく使うものをまとめました。

生成

let calendar = Calendar(identifier: .gregorian)
let date = calendar.date(from: DateComponents(year: 2016, month: 10, day: 1))
// -> 2016年10月1日 0時0分
  • Calendar.current を使用するとローカル環境によってカレンダーが変わることに注意
    • カレンダーが違うと「2016年10月1日」と言っても違う日時を指すことになるので、西暦で指定したい場合は .gregorian のカレンダーを使用すること
    • 例えば西暦 (.gregorian) 2016年 = 和暦 (.japanese) 28年
  • タイムゾーンを指定したい場合は calendar.timeZone を変更する
    • デフォルトはローカル環境のタイムゾーン

要素取得

// date: 2016年10月1日 0時0分
calendar.component(.day, from: date)
// -> 1

要素追加

// date: 2016年10月1日 0時0分
calendar.date(byAdding: .day, value: 1, to: date)
// -> 2016年10月2日 0時0分
calendar.date(byAdding: DateComponents(hour: 1, minute: 1), to: date)
// -> 2016年10月1日 1時1分
  • 週を足したい場合は weekOfYearweekOfMonth を使用

要素置き換え

// date: 2016年10月1日 0時0分
var components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second, .nanosecond], from: date)
components.month = 9
calendar.date(from: components)
// -> 2016年9月1日 0時0分
  • components.day = 32 など日の範囲を超えて指定すると月が繰り上がる
  • マイナスも指定可

要素再設定

// date: 2016年10月1日 2時34分
calendar.date(bySetting: .month, value: 9, of: date)
// -> 2017年9月1日 0時0分
  • 指定した要素にマッチするまで日時が進むor戻ることに注意
    • 上の例では、月の指定だけにも関わらず2016年から2017年まで進み、時間が0時0分に変わっている
    • 進むか戻るかは実装によるらしい
    • より詳細なコントロールが必要な場合は nextDate(after:matching:matchingPolicy:behavior:direction:) を使用すること

差の取得

// date: 2016年10月1日 0時0分
// date2: 2016年10月10日 0時0分
calendar.dateComponents([.day], from: date, to: date2).day
// -> 9

別の日時の取得

一日の初め

// date: 2016年10月1日 2時34分
calendar.startOfDay(for: date)
// -> 10月1日 0時0分

次の週末

// date: 2016年10月1日 2時34分
calendar.nextWeekend(startingAfter: date)
// -> DateInterval (2016年10月8日 0時0分 から 2016年10月10日 0時0分)
  • iOS 10 以上

判定

calendar.isDateInToday(date) // 今日か
calendar.isDateInTomorrow(date) // 明日か
calendar.isDateInWeekend(date) // 週末か
calendar.isDateInYesterday(date) // 昨日か
calendar.isDate(date, inSameDayAs: date2) // ある日と同じ日か

比較

date == date2 // 等値比較
date < date2 // 大小比較

参考

Calendar - Foundation | Apple Developer Documentation

128
122
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
128
122