LoginSignup
92
89

More than 5 years have passed since last update.

[Objective-C] NSDate周りのまとめメモ

Last updated at Posted at 2014-03-24

Objecitve-Cは慣れてくると引数が分かりやすかったりとメリットもあるんですが、とにかく最初になにかをやるのが大変なイメージです。
ていうことで、今回はNSDateクラス周りのメモです。随時更新予定。

NSDateの作成

// 今の時間
NSDate *now = [NSDate date];

// 今から3秒後
NSDate *after3 = [NSDate dateWithTimeIntervalSinceNow:3.0];

文字列からNSDateオブジェクトを作る

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

// フォーマットを文字列で指定
[dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];

// 文字列からNSDateオブジェクトを生成
NSDate *fromFormatDate = [dateFormatter dateFromString:@"2014/03/18 00:00:00"];

// 特定の日付から未来の時間(5分後)
NSDate *futerDate = [fromFormatDate initWithTimeInterval:(5 * 60) sinceDate:fromFormatDate];

日付同士を比較する

NSDate *now = [NSDate date];
NSDate *otherDate = [NSDate dateWithTimeIntervalSinceNow:5.0];

NSComparisonResult result = [now compare:otherDate];

switch (result) {
    case NSOrderedSame:
        // 同一時刻
        break;
    case NSOrderedAscending:
        // nowよりotherDateのほうが未来
        break;
    case NSOrderedDescending:
        // nowよりotherDateのほうが過去
        break;
}

日付同士の差分(経過時間)を取得する

// anyDateという、以前取得したデータがあるとする
NSDate *now = [NSDate date];

NSTimeInterval delta = [now timeIntervalSinceDate:anyDate]; // => 例えば 500.0 秒後
92
89
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
92
89