IOS 時間和時間戳之間轉化


以毫秒為整數值的時間戳轉換

  • 時間戳轉化為時間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; } 
  • 時間轉化為時間戳
   
     // 當前時間 NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0]; NSTimeInterval a=[date timeIntervalSince1970]*1000; // *1000 是精確到毫秒,不乘就是精確到秒 NSString *timeString = [NSString stringWithFormat:@"%.0f", a]; //轉為字符型 
  • 通過比較時間與當前時間返回年月日的方法
- (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 ]; }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM