web-dev-qa-db-ja.com

ミリ秒の精度でnsdateを取得する方法は?

ミリ秒の精度で時間を取得する必要があります。 NSDateから取得するにはどうすればよいですか。現在、私がNSLog時間を設定すると、最大で数秒しか表示されません。

20
sujith1406

秒を変換するには、以下の方法を使用する必要があります。ミリ秒単位:

([NSDate timeIntervalSinceReferenceDate] * 1000)
29
Jhaliya

(Javaのように)ミリ秒で時間を取得したい人のために

double timestamp = [[NSDate date] timeIntervalSince1970];
int64_t timeInMilisInt64 = (int64_t)(timestamp*1000);

(iOS7およびXcode 5を使用したiPhoneシミュレーターでテスト済み)

6

キースはミリ秒の計算については正しいですが、NSDateComponentsを使用してすべての時間コンポーネントを秒単位で取得できるため、時間間隔の小数部分のみを処理することを検討することをお勧めします。次のようなものを使用する場合は、それにミリ秒コンポーネントを追加できます。

/*This will get the time interval between the 2
  dates in seconds as a double/NSTimeInterval.*/
double seconds = [date1 timeIntervalSinceDate:date2];

/*This will drop the whole part and give you the
  fractional part which you can multiply by 1000 and
  cast to an integer to get a whole milliseconds
  representation.*/
double milliSecondsPartOfCurrentSecond = seconds - (int)seconds;

/*This will give you the number of milliseconds accumulated
  so far before the next elapsed second.*/
int wholeMilliSeconds = (int)(milliSecondsPartOfCurrentSecond * 1000.0);

お役に立てば幸いです。

4
steviesama