I am trying to create something similar to Kevin Lawler's Timeago for future dates. It seems that using dateFormatter and setting SetDoesRelativeDateFormatting:YES is the closest native api to that library or similar libraries in other languages. Apple provides the sample code below that I have working. However, its future capability is limited to swapping tomorrow for tomorrow's date and so I am trying to combine it with NSDateFormatter. For some reason, however, I can't get the two to work together.
Apple reference code:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeStyle = NSDateFormatterNoStyle;
dateFormatter.dateStyle = NSDateFormatterMediumStyle;
dateFormatter.doesRelativeDateFormatting = YES;
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:60*60*24*3];
NSString *dateString = [dateFormatter stringFromDate:date];
NSLog(@"dateString: %@", dateString); //logs valid output
If instead of using timestyle or datestyle, however, I use setDateFormat
when I log out the result, I get nil.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssz"];
dateFormatter.doesRelativeDateFormatting = YES;
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:60*60*24*3];
NSString *dateString = [dateFormatter stringFromDate:date];
NSLog(@"dateString: %@", dateString); //logs blank
Does doesRelativeDateFormatting
only work with NSDateFormatterMediumStyle
or can you combine it with setDateFormat in some way that I am not seeing?
Please use below code it worked for me
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeStyle = NSDateFormatterNoStyle;
dateFormatter.dateStyle = NSDateFormatterMediumStyle;
dateFormatter.doesRelativeDateFormatting = YES;
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:60*60*24*3];
NSString *dateString = [dateFormatter stringFromDate:date];
NSLog(@"dateString: %@", dateString); //logs valid output
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssz"];
dateFormatter.doesRelativeDateFormatting = NO;
date = [NSDate dateWithTimeIntervalSinceNow:60*60*24*3];
dateString = [dateFormatter stringFromDate:date];
NSLog(@"dateString: %@", dateString); //logs date correctly
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.