0
NSTimeInterval expirationTime = (secondsSinceUnixEpoch*1000)+120000;
expirationTime = ceil(expirationTime/2);
int expirationInt = (int)expirationTime;
NSLog(@"%d", expirationInt);

The log output is always negative, even though before I convert it to an int it's positive... I tried just multiplying it by -1 to make it positive again and it's just staying negative! I'm totally perplexed.... don't know much about C, am I just doing something silly??

eddie_cat
  • 2,527
  • 4
  • 25
  • 43
  • 2
    Have you considered overflow? – CRD Nov 13 '13 at 22:22
  • 2
    Why are you converting it to an `int`? Why not keep it as an `NSTimeInterval` (`double`)? – rmaddy Nov 13 '13 at 22:28
  • Try using `long` or `long long` if you really need an integral type. – rmaddy Nov 13 '13 at 22:28
  • Because I need it to not have decimal points. I'm putting the number into a URL. Is there a better way to get the decimal part out than converting it to int? – eddie_cat Nov 13 '13 at 22:30
  • I will try with long, thank you! – eddie_cat Nov 13 '13 at 22:30
  • The maximum `int` is about 2 billion. The current Unix epoch time in seconds is 1,384,381,689. Convert to milliseconds (as you have) and you add another 3 digits on the right. – Hot Licks Nov 13 '13 at 22:31
  • @user1714556 I posted an answer that shows how to use the `NSTimeInterval` in a URL without the need to convert it. – rmaddy Nov 13 '13 at 22:54

2 Answers2

4

The number (secondsSinceUnixEpoch*1000)+120000 looks to me like it's going to be way too large to fit in an int. Chances are the integer is overflowing and becoming negative.

paddy
  • 60,864
  • 6
  • 61
  • 103
1

Converting to long long is one solution. As you stated in a comment, you want to show a whole number for use in a URL. Just do this:

NSTimeInterval expirationTime = (secondsSinceUnixEpoch*1000)+120000;
expirationTime = ceil(expirationTime/2);
NSString *urlString = [NSString stringWithFormat:@"http://example.com?time=%.0f", expirationTime];

This will format the decimal number as a whole number.

rmaddy
  • 314,917
  • 42
  • 532
  • 579