开发者

JSON date to NSDate and back

开发者 https://www.devze.com 2023-02-06 06:55 出处:网络
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:

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://开发者_StackOverflowsomeurl?since=%qi",date];

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消