時間戳(以毫秒為整數值)與 NSDate 之間的互轉是日常開發的常見操作,這裡整理三段可直接複用的代碼。
- (NSString *)timeWithTimeIntervalString:(NSString *)timeString { // 格式化時間 NSDateFormatter* formatter = [[NSDateFormatter alloc] init]; formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"]; [formatter setDateStyle:NSDateFormatterMediumStyle]; [formatter setTimeStyle:NSDateFormatterShortStyle]; [formatter setDateFormat:@"yyyy年MM月dd日 HH:mm"]; // 毫秒值轉化為秒 NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]/ 1000.0]; NSString* dateString = [formatter stringFromDate:date]; return dateString; }
關鍵點是 dateWithTimeIntervalSince1970: 接受的是「秒」,而後端返回的多為毫秒,所以要除以 1000。同時建議顯式設置 timeZone,否則不同環境下輸出的時間可能差幾個小時。
// 當前時間 NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0]; NSTimeInterval a=[date timeIntervalSince1970]*1000; // *1000 是精確到毫秒,不乘就是精確到秒 NSString *timeString = [NSString stringWithFormat:@"%.0f", a]; //轉為字符型
需要拿到「相差幾年幾月幾天」時,用 NSCalendar 的 components 方法最省事,它會自動處理閏年、大小月等各種邊界情況,比自己做除法可靠得多。
- (void)getBabyDetailAge:(NSString *)date { // 獲得日期對象 NSDateFormatter *formatter_ = [[NSDateFormatter alloc] init]; formatter_.dateFormat = @"yyyy-MM-dd HH:mm:ss"; NSDate *createDate = [formatter_ dateFromString:date]; NSCalendar *gregorian = [[ NSCalendar alloc ] initWithCalendarIdentifier : NSCalendarIdentifierGregorian]; NSUInteger unitFlags = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear; NSDateComponents *components = [gregorian components:unitFlags fromDate:createDate toDate:[NSDate date] options: 0 ]; NSInteger years = [components year]; NSInteger months = [components month ]; NSInteger days = [components day ]; }
以上就是 iOS 中時間與時間戳互轉的實用代碼,實際使用時記得留意毫秒與秒的換算以及時區設置。