kiran kiran - 1 month ago 13
iOS Question

how to get date value when its create from current date

How to convert string date @"2016-10-19T12:37:15.0896144+00:00" int second/Min/hour/days/months/year.

I have date create value i.e @"2016-10-19T12:37:15.0896144+00:00"

**after few seconds need to show " 50 sec"

after few minutes need to show "40 min"

after few hours need to show @"20 hours"

after few days need to show @"3 days"

after few month need to show @"4 month"

after few year need to show @"2 years"**

What I tried is which i not working.

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];


Your input is highly appreciated.

Rob Rob
Answer

Use NSDateFormatter to convert your strings to dates. Then use NSDateComponentsFormatter with maximumUnitCount of 1 and allowedUnits to include seconds, minutes, hours, days, month, and year.

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];

If you're wondering about the locale setting, see Apple Technical Q&A 1480.