Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert NSDate to integer to pass PHP date() as unix timestamp?

I'm an objective-c beginner and I was assigned to create an iPhone app for our client. I have some background with Java but almost no experience in this objective-c and this is my first time to developping a complete application...

Anyway, I'm currently stack at several problems. One of those problem is that I need to send an integer value for PHP's date function from my iOS app. I've been searching around for the solution, but all of them are dealing with opposite ways (int to NSDate), not NSDate to integer value.

I tried solutions like answered here but it's obvious it returns double, not an integer...
Or this but this couldn't get the System time.

I know I could get current system's NSDate with:

NSDate *theDay = [NSDate dateWithTimeIntervalSinceNow:[[NSTimeZone systemTimeZone] secondsFromGMT]];  

But I could not figure out how to convert this to an integer (or long) value.

I just need to get the same value as we can get in Java with System.currentTimeMillis().

Also, this is my first time to ask questions here in stackoverflow. So please let me know if there's anything I should do/not to do when posting questions here, etc.

Thank you.

like image 311
Faust V Avatar asked Nov 11 '12 02:11

Faust V


1 Answers

To get the current date, you should use this:

NSDate *theDate = [NSDate date];

To get it in seconds since January 1st, 1970, as a double, you would use:

NSTimeInterval seconds = [[NSDate date] timeIntervalSince1970];

To get it in ms, simply multiply the previous value by 1000 and let the compiler cast it into an integer without needing any additional code:

long long milliseconds = [[NSDate date] timeIntervalSince1970] * 1000;

And as @HotLicks points out, while System.currentTimeMillis() is in GMT, if you need the local time, you could use:

long long milliseconds = ([[NSDate date] timeIntervalSince1970] 
                        + [[NSTimeZone defaultTimeZone] secondsFromGMT]) * 1000; 

(I think that most web services will want GMT though.)

like image 140
lnafziger Avatar answered Dec 29 '22 12:12

lnafziger