Example of conversion between IOS time and timestamp
- 2021-09-20 21:40:12
- OfStack
Timestamp conversion with milliseconds as integer value
Time stamp is converted to time NSDate
- (NSString *)timeWithTimeIntervalString:(NSString *)timeString
{
// Formatting time
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"yyyy Year MM Month dd Day HH:mm"];
// Millisecond value converted to seconds
NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]/ 1000.0];
NSString* dateString = [formatter stringFromDate:date];
return dateString;
}
Convert time to timestamp
// Current time
NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];
NSTimeInterval a=[date timeIntervalSince1970]*1000; // *1000 It is accurate to milliseconds, or it is accurate to seconds if it is not multiplied
NSString *timeString = [NSString stringWithFormat:@"%.0f", a]; // Convert to character type
Returns the year, month and day by comparing time with the current time
- (void)getBabyDetailAge:(NSString *)date
{
// Get 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 ];
}