JSON dates to NSDate and vice versa

I have a JSON date, for example: 1295804021525 , which is the number of milliseconds since 1970.

I wrote the following code to convert this number to NSDate:

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

Which works and returns the correct date. First, I wonder if this is the best way to convert.

Next, I wonder how to convert back to millisecond format, and then put in 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 can get the same functionality using NSNumber.

+4
source share
1 answer

Thanks to your initial conversion, you lose accuracy per second. You can 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 will help in any way. With the mentioned modification, both of these code fragments are simple and should work fine.

+11
source

Source: https://habr.com/ru/post/1336890/


All Articles