I want to convert nsdate in to relative format like "Today","Yesterday","a week ago","a month ago","a year ago","date as it is"
.
I have written following method for it.. but some how its just printing as it is date.. can you please tell me what should be the problem?
//Following is my function which converts the date into relative string
+(NSString *)getDateDiffrence:(NSDate *)strDate{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.timeStyle = NSDateFormatterMediumStyle;
df.dateStyle = NSDateFormatterShortStyle;
df.doesRelativeDateFormatting = YES;
NSLog(@"STRING DATEEE : %@ REAL DATE TODAY %@",[df stringFromDate:strDate],[NSDate date]);
return [df stringFromDate:strDate];
}
I have date string with the following format "2013-10-29T09:38:00"
When I tried to give the NSDate object then its always return me null date.
so I tried to convert that date in to yyyy-MM-dd HH:mm:ssZZZZ
then I pass this date to function then it's just printing whole date..
How to solve this problem?
//Following is the code I call the above function
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
NSDate *date = [formatter dateFromString:[threadDict objectForKey:@"lastMessageDate"]];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ssZZZZ"];
NSString *date1 = [formatter stringFromDate:date];
NSDate *date_d = [formatter dateFromString:date1];
NSString *resultstr=[UserManager getDateDiffrence:date];
self.dateLabel.text=resultstr;
Complate Code If Futures Dates
FOR: SWIFT 3
Here's a Swift 3 version, for past dates, that handles all units and singular or plural in the returned String.
Example Use:
I based it on a riff off of Saurabh Yadav's. Thanks.
This is just a copy of a previous answer but it returns
Just now
if it is less than five seconds.For simplicity I'm assuming that the dates you are formatting are all in the past (no "tomorrow" or "next week"). It's not that it can't be done but it would be more cases to deal with and more strings to return.
You can use
components:fromDate:toDate:options:
with whatever combination of date components you are looking for to get the number of years, months, weeks, days, hours, etc. between two dates. By then going though them in order from most significant (e.g. year) to least significant (e.g. day), you can format a string based only on the most significant component.For example: a date that is 1 week, 2 days and 7 hours ago would be formatted as "1 week".
If you want to create special strings for a special number of a unit, like "tomorrow" for "1 day ago" then you can check the value of that component after you have determined that it is the most significant component.
The code would look something like this:
If your dates could also be in the future then you can check the absolute value of the components in the same order and then check if it's positive or negative to return the appropriate strings. I'me only showing the year below: