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

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


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];