如何转换字符串日期@“2016-10-19T12:37:15.0896144 + 00:00”int second / Min / hour / days / months / year。
我有约会创造价值,即@“2016-10-19T12:37:15.0896144 + 00:00”
**几秒后需要显示“50秒”
几分钟后需要显示“40分钟”几个小时后需要显示@“20小时”
几天后需要展示@“3天”
几个月后需要显示@“4个月” 几年后需要展示@“2年”**我尝试的是我不工作的。
NSString* format = @"2016-10-19T12:37:15.0896144+00:00";
// Set up an NSDateFormatter for UTC time zone
NSDateFormatter* formatterUtc = [[NSDateFormatter alloc] init];
[formatterUtc setDateFormat:format];
[formatterUtc setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
// Cast the input string to NSDate
NSDate* utcDate = [formatterUtc dateFromString:[formatterUtc stringFromDate:timeString]];
// Set up an NSDateFormatter for the device's local time zone
NSDateFormatter* formatterLocal = [[NSDateFormatter alloc] init];
[formatterLocal setDateFormat:format];
[formatterLocal setTimeZone:[NSTimeZone localTimeZone]];
// Create local NSDate with time zone difference
NSDate* localDate = [formatterUtc dateFromString:[formatterLocal stringFromDate:utcDate]];
NSTimeInterval seconds = [[NSDate date] timeIntervalSinceDate:localDate];
非常感谢您的意见。
答案 0 :(得分:1)
使用NSDateFormatter
将字符串转换为日期。然后使用NSDateComponentsFormatter
{1}}和maximumUnitCount
来包含秒,分钟,小时,天,月和年。
allowedUnits
如果您对NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ";
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
NSDate *date1 = [dateFormatter dateFromString:@"2016-08-19T12:37:15.0896144+00:00"];
NSDate *date2 = [NSDate date]; // or, if date2 is also from a string, just use that dateFormatter again
NSDateComponentsFormatter *componentsFormatter = [[NSDateComponentsFormatter alloc] init];
componentsFormatter.unitsStyle = NSDateComponentsFormatterUnitsStyleFull;
componentsFormatter.allowedUnits = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
componentsFormatter.maximumUnitCount = 1;
NSString *string = [componentsFormatter stringFromDate:date1 toDate:date2];
设置感到疑惑,请参阅Apple Technical Q&A 1480。