Anjani G
Anjani G

Reputation: 1

How to get int value of time stamp which includes milliseconds in objective c

 NSNumber * uniqueId = [NSNumber numberWithInt:([[NSDate date] timeIntervalSince1970])];

Milliseconds is not included in the above code.If i used like below code ,it is printing negative values.

NSNumber * uniqueId1 = [NSNumber numberWithInt:([[NSDate date] timeIntervalSince1970] * 1000)];

Can we get time stamp with milliseconds as int????

Upvotes: 0

Views: 1941

Answers (3)

Adam Kaplan
Adam Kaplan

Reputation: 1962

The problem is that you are casting a floating point to an integer.

As per the documentation, timeIntervalSince1970 returns an NSTimeInterval, which is a double, not an integer.

  1. In your first code example, you're actually discarding the milliseconds by casting.
  2. In your second code example, you are overflowing the integer. After multiplying the value by 1000, it is too large to fit in an integer.

In the end, you're just doing too much code and you shouldn't need to really worry about this.

NSTimeInterval interval = [NSDate date].timeIntervalSince1970;
NSNumber *timestamp = @(interval * 1000.);

Here, I use the proper documented type of NSTimeInterval. Then I multiply that by 1,000 to change seconds to milliseconds. Finally, I use Clang literal syntax to instruct the compiler to create the appropriate NSNumber.

Upvotes: 0

Nirav Kotecha
Nirav Kotecha

Reputation: 2581

@AnjaniG you can use one of them..

NSString *strTimeStamp = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] * 1000];
int timestamps = [strTimeStamp intValue];
NSLog(@"number int = %d",timestamps);

Upvotes: 1

devliubo
devliubo

Reputation: 171

You should not use an Int, [[NSDate date] timeIntervalSince1970] * 1000 is bigger than INT_MAX. You should use long long to store the value.

NSNumber * uniqueId1 = [NSNumber numberWithLongLong:([[NSDate date] timeIntervalSince1970] * 1000)];

Upvotes: 0

Related Questions