在iOS中使用NSDate来处理时间相关的操做,这在iOS客户端开发中很是方便。若是中间层使用c++来写的话,为了保证中间层代码的纯净,不能在c++中混编OC代码,这时候就要使用c++的方法来产生13位时间戳,向外传递给OC调用,以下代码展现了如何生成13位时间戳的方式,c++
#if defined(__APPLE__) #define sprintf_s snprintf #endif time_t t = time(NULL); char timeInterval[32] = {0}; sprintf_s(timeInterval, sizeof(timeInterval), "%ld000", t); //timeInterval即为13位的时间戳。
这时候timeInterval即为c++中间层传递给OC的13位时间戳,将其转换成OC时间的方法乳腺下所示,code
//将中间层传过来的c++时间戳strtime转换成iOS中的时间 NSDateFormatter *formatter =[[NSDateFormatter alloc] init]; [formatter setDateFormat:@"MM/dd HH:mm"]; //atol()将const char*字符串转换为长整形long NSDate *currentDate = [NSDate dateWithTimeIntervalSince1970:atol(timeInterval)]; NSString *currentTime = [formatter stringFromDate:currentDate]; //currentTime就是将13位长整形转换为的OC时间