开发者

Convert MongoDB BSON ObjectId (oid) to generated time in Objective-C?

I've found this:

function: htt开发者_JAVA百科p://github.com/timburks/NuMongoDB/blob/master/src/bson.c#L128 bytes: http://github.com/timburks/NuMongoDB/blob/master/src/platform_hacks.h#L55 struct: http://github.com/timburks/NuMongoDB/blob/master/src/bson.h#L70

But how exactly would I use this for my iPhone app that gets the oid as a string from the server and want to extract the created_at timestamp? This is what I have so far. It's an Objective-C method, but can I put c code in my Objective-c .m file?

- timeFromBsonOid:(NSString *)oid {
    time_t out;
    memcpy(&out, oid, 4);
    return out;
}

Matt


You can convert the oid string to NSDate like this:

NSString *asd = @"4c8f695bdaf9856dbe000008";
long result;
BOOL success = [[NSScanner scannerWithString:[asd substringToIndex:8]] scanHexLongLong:&result];
NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:result];


Kossi's answer's a bit out of date. Make sure to use unsigned long long instead as otherwise you may notice odd behavior and crashes on 32bit and 64bit devices.

NSString *asd = @"4c8f695bdaf9856dbe000008";
unsigned long long result;
BOOL success = [[NSScanner scannerWithString:[asd substringToIndex:8]] scanHexLongLong:&result];
NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:result];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜