SoFunction
Updated on 2025-04-12

Example of conversion between IOS time and timestamp

Timestamp conversion in milliseconds as integer values

Timestamp converted to time NSDate

- (NSString *)timeWithTimeIntervalString:(NSString *)timeString
{
  // Format time  NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
   = [NSTimeZone timeZoneWithName:@"shanghai"];
  [formatter setDateStyle:NSDateFormatterMediumStyle];
  [formatter setTimeStyle:NSDateFormatterShortStyle];
  [formatter setDateFormat:@"yyyyy MM month dd day HH:mm"];
  
  // Millisecond value is converted to seconds  NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]/ 1000.0];
  NSString* dateString = [formatter stringFromDate:date];
  return dateString;
}

Time converted to timestamp

    // Current time   NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];
  NSTimeInterval a=[date timeIntervalSince1970]*1000; // *1000 is accurate to milliseconds, if not multiplied, it is accurate to seconds  NSString *timeString = [NSString stringWithFormat:@"%.0f", a]; //Convert to character type

Return to year, month and day by comparing time with the current time

- (void)getBabyDetailAge:(NSString *)date
{
  // Obtain the date object  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 ];
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.