Convertire MongoDB BSON ObjectId (OID) a tempo generato in Objective-C?
-
04-10-2019 - |
Domanda
ho trovato questo:
funzione: 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
Ma esattamente come avrei usato questo per il mio iPhone app che ottiene l'OID come una stringa dal server e desidera estrarre il timestamp created_at? Questo è ciò che ho finora. Si tratta di un metodo di Objective-C, ma posso mettere codice C nel mio file .m Objective-C?
- timeFromBsonOid:(NSString *)oid {
time_t out;
memcpy(&out, oid, 4);
return out;
}
Matt
Soluzione
È possibile convertire la stringa OID per NSDate in questo modo:
NSString *asd = @"4c8f695bdaf9856dbe000008";
long result;
BOOL success = [[NSScanner scannerWithString:[asd substringToIndex:8]] scanHexLongLong:&result];
NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:result];
Altri suggerimenti
La risposta di Kossi è un po 'fuori moda. Assicurarsi di utilizzare unsigned long long, invece, come altrimenti si può notare il comportamento strano e si schianta su dispositivi a 32bit e 64bit.
NSString *asd = @"4c8f695bdaf9856dbe000008";
unsigned long long result;
BOOL success = [[NSScanner scannerWithString:[asd substringToIndex:8]] scanHexLongLong:&result];
NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:result];