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

发布于 2024-09-24 05:31:40 字数 841 浏览 1 评论 0原文

我发现了这个:

函数: http://github. com/timburks/NuMongoDB/blob/master/src/bson.c#L128 字节: http://github.com/timburks/NuMongoDB/ blob/master/src/platform_hacks.h#L55 结构: 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;
}

马特

I've found this:

function: http://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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

遮云壑 2024-10-01 05:31:40

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

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

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];
亢潮 2024-10-01 05:31:40

科西的回答有点过时了。确保使用 unsigned 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];

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];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文