Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON date to NSDate and back

I have a JSON date, e.g: 1295804021525, which is the number of milliseconds from 1970.

I have written the following code to convert this number into an NSDate:

long long seconds = [[payload valueForKey:@"starttime"]longLongValue]/1000;  
NSDate *somedate = [NSDate dateWithTimeIntervalSince1970:seconds];

Which does work and returns the correct date. First I'm wondering if this is the best way of doing the conversion.

Next I am wondering how to convert back to the milliseconds format and then put into the url to send back to the server.

I have:

long long date = [somedate timeIntervalSince1970] * 1000;
NSString *urlString = [NSString stringWithFormat:@"http://someurl?since=%qi",date];

Again this seems to work but I was wondering how I could get the same functionality using NSNumber.

like image 512
cjroebuck Avatar asked Dec 22 '22 18:12

cjroebuck


1 Answers

With your original conversion, you're losing sub-second precision. You may want to do something like

CFTimeInterval seconds = [[payload valueForKey:@"starttime"] doubleValue] / 1000.0;

The second snippet should be fine.

I'm not sure why you think using NSNumber would help in any fashion. With the modification I mentioned, both these code snippets are straightforward and should work just fine.

like image 185
Lily Ballard Avatar answered Jan 11 '23 04:01

Lily Ballard