将MongoDB BSON ObjectId(oid)转换为Objective-C中生成的时间?

时间:2010-09-19 18:03:22

标签: iphone objective-c mongodb bson

我发现了这个:

功能:http://github.com/timburks/NuMongoDB/blob/master/src/bson.c#L128 字节:http://github.com/timburks/NuMongoDB/blob/master/src/platform_hacks.h#L55 struct:http://github.com/timburks/NuMongoDB/blob/master/src/bson.h#L70

但是我如何才能将这个用于我的iPhone应用程序,该应用程序将oid作为服务器中的字符串获取并想要提取created_at时间戳?这就是我到目前为止所拥有的。这是一个Objective-C方法,但是我可以将c代码放在Objective-c .m文件中吗?

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

马特

2 个答案:

答案 0 :(得分:6)

您可以将oid字符串转换为NSDate,如下所示:

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

答案 1 :(得分:0)

Kossi的回答有点过时了。确保使用无符号long long,否则您可能会注意到32位和64位设备上的奇怪行为和崩溃。

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