NSTimeInterval
を に変換するにはどうすればよいNSDate
ですか? ストップウォッチのようなものだと考えてください。最初の日付を 00:00:00 にしたいのですが、NSTimeInterval
X 秒です。
を使用して切り上げてNSTimeInterval
int に変換してから、を使用して文字列にスローするために a に変換する必要があるため、このようにする必要があります。lround
NSDate
NSDateFormatter
NSTimeInterval
を に変換するにはどうすればよいNSDate
ですか? ストップウォッチのようなものだと考えてください。最初の日付を 00:00:00 にしたいのですが、NSTimeInterval
X 秒です。
を使用して切り上げてNSTimeInterval
int に変換してから、を使用して文字列にスローするために a に変換する必要があるため、このようにする必要があります。lround
NSDate
NSDateFormatter
はNSTimeInterval
、その名前が示すように、 と同じものを表していませんNSDate
。AnNSDate
は瞬間です。時間間隔は時間の延長です。インターバルからポイントを獲得するには、別のポイントを獲得する必要があります。あなたの質問は、「12 インチをこのボード上のスポットに変換するにはどうすればよいですか?」と尋ねるようなものです。さて、12インチ、どこから?
基準日を選択する必要があります。NSDate
これは、カウンターを開始した時刻を表す可能性が最も高いでしょう。+[NSDate dateWithTimeInterval:sinceDate:]
次に、またはを使用できます-[NSDate dateByAddingTimeInterval:]
そうは言っても、あなたはこれについて後ろ向きに考えていると確信しています。現在の時刻ではなく、開始点、つまりintervalからの経過時間を表示しようとしています。表示を更新するたびに、新しい間隔を使用する必要があります。例(更新を行うために定期的に起動するタイマーがあると仮定します):
- (void) updateElapsedTimeDisplay: (NSTimer *)tim {
// You could also have stored the start time using
// CFAbsoluteTimeGetCurrent()
NSTimeInterval elapsedTime = [startDate timeIntervalSinceNow];
// Divide the interval by 3600 and keep the quotient and remainder
div_t h = div(elapsedTime, 3600);
int hours = h.quot;
// Divide the remainder by 60; the quotient is minutes, the remainder
// is seconds.
div_t m = div(h.rem, 60);
int minutes = m.quot;
int seconds = m.rem;
// If you want to get the individual digits of the units, use div again
// with a divisor of 10.
NSLog(@"%d:%d:%d", hours, minutes, seconds);
}
との間の簡単な変換を次に示します。
NSDate * now = [NSDate date];
NSTimeInterval tiNow = [now timeIntervalSinceReferenceDate];
NSDate * newNow = [NSDate dateWithTimeIntervalSinceReferenceDate:tiNow];
オーレ・K・ホーンネス
NSDateFormatter
時間間隔を表示したい場合は、使用しないことをお勧めします。NSDateFormatter
ローカルまたは特定のタイムゾーンで時間を表示したい場合に便利です。ただし、この場合、時間がタイムゾーンに調整されているとバグになります (たとえば、1 年に 1 日は 23 時間です)。
NSTimeInterval time = ...;
NSString *string = [NSString stringWithFormat:@"%02li:%02li:%02li",
lround(floor(time / 3600.)) % 100,
lround(floor(time / 60.)) % 60,
lround(floor(time)) % 60];
最初の日付をNSDate
オブジェクトに保存している場合は、将来の任意の間隔で新しい日付を取得できます。単にdateByAddingTimeInterval:
次のように使用します。
NSDate * originalDate = [NSDate date];
NSTimeInterval interval = 1;
NSDate * futureDate = [originalDate dateByAddingTimeInterval:interval];
Apple開発者経由:
//1408709486 - 時間間隔値
NSDate *lastUpdate = [[NSDate alloc] initWithTimeIntervalSince1970:1408709486];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
NSLog(@"date time: %@", [dateFormatter stringFromDate:lastUpdate]);
日付時刻: 2014 年 8 月 22 日、午後 3 時 11 分 26 秒
NSTimeInterval
NSDate
Swift での変換:
let timeInterval = NSDate.timeIntervalSinceReferenceDate() // this is the time interval
NSDate(timeIntervalSinceReferenceDate: timeInterval)