LoginSignup
2
2

More than 3 years have passed since last update.

【Objective-C】NSDateまとめ

Posted at

現在時刻の取得

//今の時刻が取得できる
NSDate *now = [NSDate date];

現在より後の時刻の取得

//今から10秒後の時刻を取得
NSDate *afterTime = [NSDate dateWithTimeIntervalSinceNow:10.0];

文字列をNSDateに変換

//NSDate型に変換するためのフォーマットを初期化
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

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

// 先ほどのフォーマットに会う形の文字列をNSDateに変換
NSDate *fromFormatDate = [dateFormatter dateFromString:@"2020/07/01 00:00:00"];

// 先ほど変換した時間から1時間後の時刻を取得
NSDate *afterHour = [fromFormatDate initWithTimeInterval:(60 * 60) sinceDate:fromFormatDate];

NSDateの比較

//時刻の取得
NSDate *now = [NSDate date];
NSDate *otherDate = [NSDate dateWithTimeIntervalSinceNow:10.0];

//compareメソッドで比較
NSComparisonResult result = [now compare:otherDate];

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

NSDateの差分を取得

// pastという、以前取得したデータがあるとする
NSDate *now = [NSDate date];
//timeIntervalSinceDateで比較し、経過時間を取得
NSTimeInterval intervalTime = [now timeIntervalSinceDate:past];
2
2
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
2
2